Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python inst/klass instead of self?

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?

like image 596
Pithikos Avatar asked Feb 20 '15 10:02

Pithikos


2 Answers

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.

like image 196
Martijn Pieters Avatar answered Oct 04 '22 23:10

Martijn Pieters


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

like image 44
Eugene Soldatov Avatar answered Oct 04 '22 21:10

Eugene Soldatov