Python中的泛型方法

10 投票
3 回答
14807 浏览
提问于 2025-04-16 20:12

在Python中,有没有办法实现一种通用的方法处理器,让我们可以调用那些并不存在的函数?就像下面这样:

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

fb = FooBar()
fb.helloThere()

-- output --
helloThere

3 个回答

4

好的,下面是你提供的内容:

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

a = FooBar()
a.helloThere()

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

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

16

首先要记住的是,方法其实就是一些可以被调用的属性。

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

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

撰写回答