Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it considered bad practice to hardcode the name of a class inside that class's methods?

Tags:

python

oop

In python, why is it a bad thing to do something like this:

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)

The area method could be defined as follows:

def area(self): return self.__class__.pi * squared(self.radius) 

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.

like image 710
weeCoder Avatar asked Feb 07 '23 04:02

weeCoder


1 Answers

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:

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

class Square(Rectangle):
    name = "Square"

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

like image 130
sarnthil Avatar answered Feb 08 '23 17:02

sarnthil