【问题标题】:Python: Dynamically assign class methodsPython:动态分配类方法
【发布时间】:2013-01-13 10:57:58
【问题描述】:

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

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 函数。

【问题讨论】:

  • 我能问一下用例是什么吗?
  • 这是用于移动代码的,其中父对象可能有也可能没有碰撞属性。在 _call_ 中,当你有属性时,需要两个参数,如果没有属性,则不需要。我想这样做而不是使用默认参数,这样如果我忘记将这些参数提供给需要它的人,它就会出错(而如果我使用默认参数,你就不会收到这样的错误

标签: python class dynamic methods


【解决方案1】:

你不能用__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)

【讨论】:

  • 嗯 - “你需要”并不完全准确 - 因为你可以“元”这种事情,但这是最明智的,因为对为什么缺乏任何进一步的理解?
  • @JonClements -- 我对元类还不是很满意 -- 随意发布解决方案。我相信我可以从中学到一两件事:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-14
  • 2011-01-08
  • 1970-01-01
  • 1970-01-01
  • 2015-02-07
相关资源
最近更新 更多