Python inst/klass而不是self?

Pit*_*kos 5 python class naming-conventions instance

有时self可以表示类的实例,有时也可以表示类本身.那么我们为什么不使用instklass不是self?这会不会让事情变得更容易?

现在的情况如何

class A:
  @classmethod
  def do(self): # self refers to class
    ..

class B:
  def do(self): # self refers to instance of class
    ..
Run Code Online (Sandbox Code Playgroud)

我认为他们应该如何

class A:
  @classmethod
  def do(klass): # no ambiguity
    ..

class B:
  def do(inst): # no ambiguity
    ..
Run Code Online (Sandbox Code Playgroud)

那么为什么我们不在Python禅宗中这样编程,而是声明显式优于隐式?有什么东西我错过了吗?

Mar*_*ers 9

稍后在Python中添加了类方法支持,并且self已经建立了用于实例的约定.保持该惯例稳定比转换为更长的名称更有价值instance.

类方法的约定是使用名称cls:

class A:
    @classmethod
    def do(cls):
Run Code Online (Sandbox Code Playgroud)

换句话说,这些约定已经用于区分类对象和实例; 从不使用self类方法.

另见PEP 8 - 函数和方法参数:

始终self用于实例方法的第一个参数.

始终cls用于类方法的第一个参数.