是否有可能在python中实现泛型方法处理程序,允许调用不存在的函数?像这样的东西:
class FooBar:
def __generic__method__handler__(.., methodName, ..):
print methodName
fb = FooBar()
fb.helloThere()
-- output --
helloThere
Run Code Online (Sandbox Code Playgroud)
Dav*_*ebb 14
要记住的第一件事是方法是恰好可调用的属性.
>>> s = " hello "
>>> s.strip()
'hello'
>>> s.strip
<built-in method strip of str object at 0x000000000223B9E0>
Run Code Online (Sandbox Code Playgroud)
因此,您可以像处理不存在的属性一样处理不存在的方法.
这通常是通过定义__getattr__
方法来完成的.
现在你将遇到额外的复杂性,这是功能和方法之间的差异.需要将方法绑定到对象.您可以查看此问题以进行讨论.
所以我想你会想要这样的东西:
import types
class SomeClass(object):
def __init__(self,label):
self.label = label
def __str__(self):
return self.label
def __getattr__(self, name):
# If name begins with f create a method
if name.startswith('f'):
def myfunc(self):
return "method " + name + " on SomeClass instance " + str(self)
meth = types.MethodType(myfunc, self, SomeClass)
return meth
else:
raise AttributeError()
Run Code Online (Sandbox Code Playgroud)
这使:
>>> s = SomeClass("mytest")
>>> s.f2()
'method f2 on SomeClass instance mytest'
>>> s.f2
<bound method SomeClass.myfunc of <__main__.SomeClass object at 0x000000000233EC18>>
Run Code Online (Sandbox Code Playgroud)
但是,我可能会建议不要使用它.如果你告诉我们你试图解决的问题,我希望有人可以提出更好的解决方案.
def __getattr__(self, name):
#return your function here...
Run Code Online (Sandbox Code Playgroud)