【发布时间】:2017-11-22 22:23:36
【问题描述】:
假设我有这门课:
class Test(object):
def __init__(self, a):
self.a = a
def test(self, b):
if isinstance(self, Test):
return self.a + b
else:
return self + b
在我的世界中,理想情况下会这样做:
>>> Test.test(1,2)
3
>>> Test(1).test(2)
3
现在这不起作用,因为您收到此错误:
TypeError: unbound method test() must be called with Test instance as first argument (got int instance instead)
在 python3 中这工作正常,我偷偷怀疑这可以通过 python2 中的装饰器实现,但我的 python foo 不够强大,无法让它工作。
Plot Twist:那么当我需要一些东西而不是静态调用时会发生什么。
【问题讨论】:
-
哎呀,只需添加
@staticmethod装饰器就可以了...
标签: python python-2.x