为什么一个类可以从另一个类调用魔术方法


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的方法。您不会以某种方式使strExample的实例上调用some_method。Python的语法根本不是这样工作的。在这两种情况下,您都试图调用str本身的方法。目前还不清楚你想做什么,但也许str(Example().some_method())更像你想要的。

最新更新