Python中的通用方法

10

在Python中,是否可以实现通用方法处理程序,以允许调用不存在的函数?就像这样:

class FooBar:
  def __generic__method__handler__(.., methodName, ..):
    print methodName

fb = FooBar()
fb.helloThere()

-- output --
helloThere

这仍然留下了一个问题,为什么你想要这样做。 - Chris Morgan
@ChrisMorgan 它可能允许使用正则表达式自动生成方法名称,因此任何与正则表达式匹配的方法名称都可以用作特定方法的别名。 - Anderson Green
@AndersonGreen:但是你为什么想要这样做呢? - Chris Morgan
1
@ChrisMorgan 你觉得如何使用通用装饰器,对一个对象进行一些修饰(例如日志记录、延迟初始化等),并应用于其所有方法? - Tregoreg
3个回答

15

首先要记住的是,方法是可调用的属性。

>>> 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>>

然而,我可能会建议不要使用这个。如果你告诉我们你想解决的问题,我相信这里会有人能提出更好的解决方案。


如何使属性可调用? - paweloque
2
非常感谢!我想知道这个不仅是因为我需要它来解决一个具体的问题,而且也为了更好地理解Python。 - paweloque
“types.MethodType” 调用会永久地将函数分配给类吗? - paweloque
它并不会改变myfunc。它只是创建了一个名为meth的新方法,该方法是SomeClass的实例方法(绑定到self),但它并不会改变myfunc。就像l=[3,5]一样,t=tuple(l)并不会改变l - Veky

6
def __getattr__(self, name):
  #return your function here...

3
方法是可调用的属性。它们也可以使用getattr查找。 - Noufal Ibrahim

4
class FooBar:
    def __getattr__(self, name):
        def foo():
            print name
        return foo

a = FooBar()
a.helloThere()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接