class Example:
def __init__(self):
print("init called")
def some_method(self):
print("some method called")
当拥有函数的类的对象作为参数传递时,为什么一个类可以调用另一个类的构造函数。例如,str
调用Example
类的__init__
方法。以下线路运行平稳
str.__init__(Example())
但是当我使用str
调用非魔术方法时,在这种情况下是some_method
,
str.some_method(Example())
它显示以下错误
AttributeError: type object 'str' has no attribute 'some_method'
我知道类方法不应该这样使用,但我想知道这种行为的原因
str.__init__(Example())
正在调用str
的__init__
方法。Example
的__init__
运行的唯一原因是代码Example()
运行它。因此,str.some_method(Example())
失败是因为str
没有名为some_method
的方法。您不会以某种方式使str
在Example
的实例上调用some_method
。Python的语法根本不是这样工作的。在这两种情况下,您都试图调用str
本身的方法。目前还不清楚你想做什么,但也许str(Example().some_method())
更像你想要的。