为什么调用gettatr方法需要显式传递self?

问题描述 投票:0回答:1

请考虑以下代码(有效)

class AAA:

    def run(self):
        getattr(AAA, 'meth')(what='hello')

    @staticmethod
    def meth(what):
        print(what)

AAA().run()

我将需要在meth()中使用实例对象的属性,因此meth()不再是静态的。我试图做

class AAA:

    def __init__(self):
        self.who = 'John'

    def run(self):
        getattr(AAA, 'meth')(what='hello')

    def meth(self, what):
        print(f"{what} {self.who}")

AAA().run()

但是这会导致崩溃

Traceback (most recent call last):
  File "C:/scratch_15.py", line 12, in <module>
    AAA().run()
  File "C:/scratch_15.py", line 7, in run
    getattr(AAA, 'meth')(what='hello')
TypeError: meth() missing 1 required positional argument: 'self'

然后我将代码更正为

class AAA:

    def __init__(self):
        self.who = 'John'

    def run(self):
        getattr(AAA, 'meth')(self, what='hello')

    def meth(self, what):
        print(f"{what} {self.who}")

AAA().run()

# outputs "hello John"

为什么在上述情况下调用方法时为什么必须显式传递self

python python-3.x class methods self
1个回答
0
投票

getattr(AAA, 'meth')完全等于AAA.meth;您没有在属性查找中涉及绑定到self的实例,因此您将获得原始函数,而不是method对象。

相反,将self作为第一个参数传递:

    def run(self, methodname):
        getattr(self, methodname)(what='hello')  # self.meth(what='hello')
© www.soinside.com 2019 - 2024. All rights reserved.