这在 Python 3 中非常简单。下面是示例:
class C:
def __init__(self, name, age):
self.name = name
self.age = age
def m(self, x):
print(f"{self.name} called with param '{x}'")
return
ci = C("Joe", 10)
print(C)
print(ci)
print(C.m)
print(ci.m)
print(getattr(ci,'m'))
getattr(ci,'m')('arg')
<class '__main__.C'>
<__main__.C object at 0x000001AF4025FF28>
<function C.m at 0x000001AF40272598>
<bound method C.m of <__main__.C object at 0x000001AF4025FF28>>
<bound method C.m of <__main__.C object at 0x000001AF4025FF28>>
Joe called with param 'arg'
请注意,getattr来自内置模块,在我们的例子中接受两个参数,类实例ci
和表示函数名称的字符串。
我们还可以定义参数的默认值。
def m(self, x=None):
print(f"{self.name} caled with param '{x}'")
return
在这种情况下,我们可以调用:
getattr(ci,'m')()