按名称调用Python方法
如果字符串中有一个对象和一个方法名,如何调用该方法按名称调用Python方法,python,Python,如果字符串中有一个对象和一个方法名,如何调用该方法 class Foo: def bar1(self): print 1 def bar2(self): print 2 def callMethod(o, name): ??? f = Foo() callMethod(f, "bar1") 使用内置功能: class Foo: def bar1(self): print(1) def bar2(self
class Foo:
def bar1(self):
print 1
def bar2(self):
print 2
def callMethod(o, name):
???
f = Foo()
callMethod(f, "bar1")
使用内置功能:
class Foo:
def bar1(self):
print(1)
def bar2(self):
print(2)
def call_method(o, name):
return getattr(o, name)()
f = Foo()
call_method(f, "bar1") # prints 1
还可以使用按名称设置类属性
getattr(globals()['Foo'](), 'bar1')()
getattr(globals()['Foo'](), 'bar2')()
不需要先实例化Foo 我有类似的问题,想通过引用调用实例方法。以下是我发现的有趣的事情:
def callmethod(cls, mtd_name):
method = getattr(cls, mtd_name)
method()
instance_of_foo=Foo()
method_ref=getattr(Foo, 'bar')
method_ref(instance_of_foo) # instance_of_foo becomes self
instance_method_ref=getattr(instance_of_foo, 'bar')
instance_method_ref() # instance_of_foo already bound into reference
Python真是太棒了 这里是一个使用Python装饰器的更通用的版本。你可以叫短名字或长名字。我发现它在使用长短子命令实现CLI时非常有用 Python装饰器非常棒。Bruce Eckel(用Java思考)在这里漂亮地描述了Python装饰器
这只是一个例子,我有一个真实类的真实实例!调用未初始化类的方法可能意味着您做错了什么。如果
foo
不在globals中怎么办?它可能不在globals中,但您应该注意foo
不在globals中我在文档中找不到要搜索的内容!谢谢@爵士乐,这是内置的。我知道,您可能需要使用C-f
@aaronastering进行页面内搜索,但我找不到要搜索的单词!为什么callMethod(f,“bar1”)不被称为f.callMethod(f,“bar1”)PhilipJ,因为它只是一个在Foo:class之外的几行之前定义的方法。虽然它们很相似,但这并不是一个精确的复制,它询问的是模块中的函数,而不是对象的方法。非常密切相关(见鬼,甚至可能是复制):。方法也是属性。
#!/usr/bin/env python2
from functools import wraps
class CommandInfo(object):
cmds = []
def __init__(self, shortname, longname, func):
self.shortname = shortname
self.longname = longname
self.func = func
class CommandDispatch(object):
def __init__(self, shortname, longname):
self.shortname = shortname
self.longname = longname
def __call__(self, func):
print("hello from CommandDispatch's __call__")
@wraps(func)
def wrapped_func(wself, *args, **kwargs):
print('hello from wrapped_func, args:{0}, kwargs: {1}'.format(args, kwargs))
func(wself, *args, **kwargs)
ci = CommandInfo
ci.cmds += [ci(shortname=self.shortname, longname=self.longname, func=func)]
return wrapped_func
@staticmethod
def func(name):
print('hello from CommandDispatch.func')
for ci in CommandInfo.cmds:
if ci.shortname == name or ci.longname == name:
return ci.func
raise RuntimeError('unknown command')
@CommandDispatch(shortname='co', longname='commit')
def commit(msg):
print('commit msg: {}'.format(msg))
commit('sample commit msg') # Normal call by function name
cd = CommandDispatch
short_f = cd.func(name='co') # Call by shortname
short_f('short sample commit msg')
long_f = cd.func(name='commit') # Call by longname
long_f('long sample commit msg')
class A(object):
@CommandDispatch(shortname='Aa', longname='classAmethoda')
def a(self, msg):
print('A.a called, msg: {}'.format(msg))
a = A()
short_fA = cd.func(name='Aa')
short_fA(a, 'short A.a msg')
long_fA = cd.func(name='classAmethoda')
long_fA(a, 'short A.a msg')