为什么在Python类中有时使用cls而不是self作为参数?

例如:

class Person:
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname

    @classmethod
    def from_fullname(cls, fullname):
        cls.firstname, cls.lastname = fullname.split(' ', 1)

我无法通过错误:

Traceback (most recent call last):
  File "C:\Users\Dom\Desktop\test\test.py", line 7, in <module>
    p = Pump.getPumps()
TypeError: getPumps() missing 1 required positional argument: 'self'

我检查了几个教程,但似乎与我的代码没有任何不同。我唯一能想到的是Python 3.3需要不同的语法。

class Pump:

    def __init__(self):
        print("init") # never prints

    def getPumps(self):
        # Open database connection
        # some stuff here that never gets executed because of error
        pass  # dummy code

p = Pump.getPumps()

print(p)

如果我理解正确,self会自动传递给构造函数和方法。我哪里做错了?

如果我有课……

class MyClass:

    def method(arg):
        print(arg)

... 我用来创建一个对象…

my_object = MyClass()

... 我调用方法(“foo”),就像这样…

>>> my_object.method("foo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method() takes exactly 1 positional argument (2 given)

... 为什么Python告诉我我给了它两个参数,而我只给了一个?

我正在学习Python编程语言,我遇到了一些我不完全理解的东西。

在如下方法中:

def method(self, blah):
    def __init__(?):
        ....
    ....

self做什么?这意味着什么?这是强制性的吗?

__init__方法是做什么的?为什么有必要?(等)

我认为它们可能是面向对象结构,但我知道的不多。

想想这个例子:

class MyClass:
    def func(self, name):
        self.name = name

我知道self引用MyClass的特定实例。但是为什么func必须显式地包含self作为参数呢?为什么我们需要在方法的代码中使用self ?其他一些语言将其隐式化,或者使用特殊的语法。


有关设计决策的语言无关性考虑,请参见强制显式使用this/self指针的好处是什么?

要关闭OP省略方法的self形参并获得TypeError的调试问题,请使用TypeError: method()接受1个位置参数,但给出了2个。如果OP省略了self。在方法体中得到一个NameError,考虑如何在类中调用函数?