【问题标题】:Python reflection, getter to methodsPython反射,方法的getter
【发布时间】:2020-08-03 12:48:22
【问题描述】:
class A:
    def __init__(self):
        self.var = 10
    def print(self):
        print("hiiiiii")

对于 A 的对象,我们可以通过getattrsetattr 轻松访问属性。 Python中是否有任何方法可以拥有类的实例和方法名称并间接调用它,例如:

MagicalMethod( A(), "print" )

然后为我打印“hiiiiii”。

【问题讨论】:

  • getattr(A(), "print")()?方法只是可调用的属性。
  • 是的,这意味着通过传递像 A() 这样的类的实例以及它调用 A() 的方法的方法名称
  • 但是你说的不管用但也不抛出异常
  • 确实工作。
  • 是的,谢谢,伙计,我的错 ;)

标签: python reflection getattr setattr


【解决方案1】:

那就是getattr:

>>> getattr(A(), 'print')()
hiiiiii

(请注意,您仍然需要调用getattr 的返回值;您可以定义一个包装器来为您执行此操作:

def MagicalMethod(obj, name, *args, **kwargs):
    return getattr(obj, name)(*args, **kwargs)

)

operator.methodcaller 提供了一种稍微不同的间接方式。

>>> from operator import methodcaller
>>> f = methodcaller('print')
>>> f(A())
hiiiiii

【讨论】:

  • 非常感谢,对于 getattr,我没有放括号,所以它不起作用,再次感谢你 :)
猜你喜欢
  • 1970-01-01
  • 2012-09-10
  • 1970-01-01
  • 2016-04-28
  • 2012-04-18
  • 2013-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多