Why is it considered bad practice to hardcode the name of a class inside that class's methods?
<p>In python, why is it a bad thing to do something like this:</p>

<pre><code>class Circle:
  pi = 3.14159 # class variable
  def __init__(self, r = 1):
    self.radius = r
  def area(self):
    return Circle.pi * squared(self.radius)

def squared(base): return pow(base, 2)
</code></pre>

<p>The area method could be defined as follows:</p>

<pre><code>def area(self): return self.__class__.pi * squared(self.radius) 
</code></pre>

<p>which is, unless I'm very much mistaken, considered a better way to reference a class variable. The question is why? Intuitively, I don't like it but I don't seem to completely understand this.</p>

<p>Because in case you subclass the class it will no longer refer to the class, but its parent. In your case it really doesn't make a difference, but in many cases it does:</p>

<pre><code>class Rectangle(object):
    name = "Rectangle"
    def print_name(self):
        print(self.__class__.name) # or print(type(self).name)

class Square(Rectangle):
    name = "Square"
</code></pre>

<p>If you instantiate <code>Square</code> and then call its <code>print_name</code> method, it'll print "Square". If you'd use <code>Rectangle.name</code> instead of <code>self.__class__.name</code> (or <code>type(self).name</code>), it'd print "Rectangle".</p>

python oop