在Python中,是否可以实现通用方法处理程序,以允许调用不存在的函数?就像这样:
class FooBar:
def __generic__method__handler__(.., methodName, ..):
print methodName
fb = FooBar()
fb.helloThere()
-- output --
helloThere
在Python中,是否可以实现通用方法处理程序,以允许调用不存在的函数?就像这样:
class FooBar:
def __generic__method__handler__(.., methodName, ..):
print methodName
fb = FooBar()
fb.helloThere()
-- output --
helloThere
首先要记住的是,方法是可调用的属性。
>>> s = " hello "
>>> s.strip()
'hello'
>>> s.strip
<built-in method strip of str object at 0x000000000223B9E0>
因此,您可以处理不存在的方法,就像处理不存在的属性一样。
通常通过定义__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()
这将会给出:
>>> s = SomeClass("mytest")
>>> s.f2()
'method f2 on SomeClass instance mytest'
>>> s.f2
<bound method SomeClass.myfunc of <__main__.SomeClass object at 0x000000000233EC18>>
然而,我可能会建议不要使用这个。如果你告诉我们你想解决的问题,我相信这里会有人能提出更好的解决方案。
myfunc
。它只是创建了一个名为meth
的新方法,该方法是SomeClass
的实例方法(绑定到self
),但它并不会改变myfunc
。就像l=[3,5]
一样,t=tuple(l)
并不会改变l
。 - Vekydef __getattr__(self, name):
#return your function here...
class FooBar:
def __getattr__(self, name):
def foo():
print name
return foo
a = FooBar()
a.helloThere()