Sometimes self can denote the instance of the class and sometimes the class itself. So why don't we use inst
and klass
instead of self
? Wouldn't that make things easier?
How things are now
class A:
@classmethod
def do(self): # self refers to class
..
class B:
def do(self): # self refers to instance of class
..
How I think they should be
class A:
@classmethod
def do(klass): # no ambiguity
..
class B:
def do(inst): # no ambiguity
..
So how come we don't program like this when in the zen of Python it is stated that explicit is better than implicit? Is there something that I am missing?
Class method support was added much later to Python, and the convention to use self
for instances had already been established. Keeping that convention stable has more value than to switch to a longer name like instance
.
The convention for class methods is to use the name cls
:
class A:
@classmethod
def do(cls):
In other words, the conventions are already there to distinguish between a class object and the instance; never use self
for class methods.
Also see PEP 8 - Function and method arguments:
Always use
self
for the first argument to instance methods.Always use
cls
for the first argument to class methods.
I think it would be better to use "cls":
class A:
@classmethod
def do(cls): # cls refers to class
..
class B:
def do(self): # self refers to instance of class
..
It's requirement of PEP8:
http://legacy.python.org/dev/peps/pep-0008/#function-and-method-arguments
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With