【发布时间】: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