Why is it considered bad practice to hardcode the name of a class inside that class's methods?
It's not. I don't know why you think it is.
There are plenty of good reasons to hardcode the name of a class inside its methods. For example, using super
on Python 2:
super(ClassName, self).whatever()
People often try to replace this with super(self.__class__, self).whatever()
, and they are dead wrong to do so. The first argument must be the actual class the super
call occurs in, not self.__class__
, or the lookup will find the wrong method.
Another reason to hardcode the class name is to avoid overrides. For example, say you've implemented one method using another, as follows:
class Foo(object):
def big_complicated_calculation(self):
return # some horrible mess
def slightly_different_calculation(self):
return self.big_complicated_calculation() + 2
If you want slightly_different_calculation
to be independent of overrides of big_complicated_calculation
, you can explicitly refer to Foo.big_complicated_calculation
:
def slightly_different_calculation(self):
return Foo.big_complicated_calculation(self) + 2
Even when you do want to pick up overrides, it's usually better to change ClassName.whatever
to self.whatever
instead of self.__class__.whatever
.