在下面的代码中,为什么最后一行执行会出错? x.bf()中的点运算符不应该将实例'x'传递给函数bf(就像x.af()那样)?
class A:
a = 6
def af (self):
return "Hello-People"
class B:
b = 7
def bf (self):
return "Bye-People"
>>> x = A()
>>> b = B()
>>> x.bf = B.bf
>>> x.bf()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bf() missing 1 required positional argument: 'self'
答案 0 :(得分:1)
x.bf = B.bf是您的错误,因为B是一个类,而不是该对象的实例。
您无法直接将x.bf分配给该课程。 您需要将x.bf分配给实例&#39; b.bf&#39;或者正确地实例化
即。将该行更改为:
# Where we instantiated class B and invoke bf via lazy loading (loading at the last possible minute)
x.bf = B().bf
或
# Use the existing instance of B and call bf
x.bf = b.bf
更多信息:
每当实例化一个类时,都需要遵循它的构造函数签名。在这种情况下,除了self之外,类不需要其他参数。但是,如果通过();
调用类,则仅传递self&#39; x = A()&#39;和&#39; b = B()&#39;符合该签名
你遇到的错误基本上是python告诉你,你调用了某个东西,一个函数或一个类而没有传入一个必需的变量。