Python:动态分配类方法

0 投票
1 回答
705 浏览
提问于 2025-04-17 14:06

基本上,我想实现的是这个:

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 个回答

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)

撰写回答