Python:动态分配类方法

时间:2013-01-29 19:00:16

标签: python class dynamic methods

基本上这就是我想要完成的事情:

class Move(object):
    def __init__(self, Attr):
        if Attr:
            self.attr = Attr

        if hasattr(self, "attr"):
            __call__ = self.hasTheAttr
        else:
            __call__ = self.hasNoAttr

    def hasNoAttr(self):
        #no args!

    def hasTheAttr(func, arg1, arg2):
        #do things with the args

    __call__ = hasNoAttr

我知道这不起作用,它只是一直使用hasNoAttr。我的第一个想法是使用一个装饰器,但我并不熟悉它们,我无法弄清楚如何根据类属性是否存在来确定它。

实际问题部分:我如何根据条件确定性地使x函数或y函数成为函数。

1 个答案:

答案 0 :(得分:3)

你无法用__call__真正做到这一点 - 使用其他(非魔法)方法,你可以对它们进行修补,但使用__call__和其他魔术方法你需要委托魔术方法本身的适当方法:

class Move(object):
    def __init__(self, Attr):
        if Attr:
            self.attr = Attr

        if hasattr(self, "attr"):
            self._func = self.hasTheAttr
        else:
            self._func = self.hasNoAttr

    def hasNoAttr(self):
        #no args!

    def hasTheAttr(func, arg1, arg2):
        #do things with the args

    def __call__(self,*args):
        return self._func(*args)
相关问题