19

我有一个对象层次结构,其中几乎所有方法都是类方法。它如下所示:

class ParentObject(object):
    def __init__(self):
        pass

    @classmethod
    def smile_warmly(cls, the_method):
        def wrapper(kls, *args, **kwargs):
            print "-smile_warmly - "+kls.__name__
            the_method(*args, **kwargs)
        return wrapper

    @classmethod
    def greetings(cls):
        print "greetings"

class SonObject(ParentObject):
    @classmethod
    def hello_son(cls):
        print "hello son"

    @classmethod
    def goodbye(cls):
        print "goodbye son"

class DaughterObject(ParentObject):
    @classmethod
    def hello_daughter(cls):
        print "hello daughter"

    @classmethod
    def goodbye(cls):
        print "goodbye daughter"

if __name__ == '__main__':
    son = SonObject()
    son.greetings()
    son.hello_son()
    son.goodbye()
    daughter = DaughterObject()
    daughter.greetings()
    daughter.hello_daughter()
    daughter.goodbye()

给定的代码输出以下内容:

greetings
hello son
goodbye son
greetings
hello daughter
goodbye daughter

我希望代码输出以下内容:

-smile_warmly - SonObject
greetings
-smile_warmly - SonObject
hello son
-smile_warmly - SonObject
goodbye son
-smile_warmly - DaughterObject
greetings
-smile_warmly - DaughterObject
hello daughter
-smile_warmly - DaughterObject
goodbye daughter

但我不想@smile_warmly在每个方法之前添加这一行(当我尝试在上面的代码中这样做时,我收到错误消息TypeError: 'classmethod' object is not callable)。相反,我希望每个方法的装饰在方法中以编程方式进行__init__()

是否可以在 Python 中以编程方式装饰方法?

编辑:发现了一些似乎有效的东西——见下面我的回答。感谢布伦巴恩。

4

2 回答 2

34

装饰器所做的只是返回一个新函数。这个:

@deco
def foo():
    # blah

与此相同:

def foo():
    # blah
foo = deco(foo)

您可以随时做同样的事情,无需@语法,只需将函数替换为您喜欢的任何内容。因此,__init__在其他地方或任何地方,您都可以遍历所有方法,并为每个方法替换为smilewarmly(meth).

但是,与其在 中执行此__init__操作,不如在创建类时执行此操作更有意义。您可以使用元类或更简单地使用类装饰器来做到这一点:

def smileDeco(func):
    def wrapped(*args, **kw):
        print ":-)"
        func(*args, **kw)
    return classmethod(wrapped)

def makeSmiley(cls):
    for attr, val in cls.__dict__.iteritems():
        if callable(val) and not attr.startswith("__"):
            setattr(cls, attr, smileDeco(val))
    return cls

@makeSmiley
class Foo(object):
    def sayStuff(self):
        print "Blah blah"

>>> Foo().sayStuff()
:-)
Blah blah

在这个例子中,我将 classmethod 装饰放在了我的smileDeco装饰器中。你也可以把它放进去,makeSmiley以便makeSmiley返回smileDeco(classmethod(val))。(您想采用哪种方式取决于微笑装饰器与作为类方法的事物的联系程度。)这意味着您不必@classmethod在类内部使用。

此外,当然,在循环中,makeSmiley您可以包含您想要决定(例如,基于方法的名称)是否用微笑行为包装它的任何逻辑。

请注意,如果您真的想在类中手动使用,则必须更加小心@classmethod,因为通过类访问的类__dict__方法是不可调用的。所以你必须专门检查对象是否是一个类方法对象,而不是仅仅检查它是否是可调用的。

于 2012-12-30T23:21:08.630 回答
1

此解决方案产生我想要的输出:

class ParentObject(object):
    def __init__(self):
        self._adjust_methods(self.__class__)

    def _adjust_methods(self, cls):
        for attr, val in cls.__dict__.iteritems():
            if callable(val) and not attr.startswith("_"):
                setattr(cls, attr, self._smile_warmly(val))
        bases = cls.__bases__
        for base in bases:
            self._adjust_methods(base)

    def _smile_warmly(self, the_method):
        def _wrapped(self, *args, **kwargs):
            print "-smile_warmly - " +self.__name__
            the_method(self, *args, **kwargs)
        cmethod_wrapped = classmethod(_wrapped)
        # cmethod_wrapped.adjusted = True
        return cmethod_wrapped

    def greetings(self):
        print "greetings"

class SonObject(ParentObject):
    def hello_son(self):
        print "hello son"

    def goodbye(self):
        print "goodbye son"

class DaughterObject(ParentObject):
    def hello_daughter(self):
        print "hello daughter"

    def goodbye(self):
        print "goodbye daughter"

if __name__ == '__main__':
    son = SonObject()
    son.greetings()
    son.hello_son()
    son.goodbye()
    daughter = DaughterObject()
    daughter.greetings()
    daughter.hello_daughter()
    daughter.goodbye()

输出是:

-smile_warmly - SonObject
greetings
-smile_warmly - SonObject
hello son
-smile_warmly - SonObject
goodbye son
-smile_warmly - DaughterObject
greetings
-smile_warmly - DaughterObject
hello daughter
-smile_warmly - DaughterObject
goodbye daughter
于 2012-12-31T02:18:08.700 回答