【发布时间】:2008-11-20 08:40:40
【问题描述】:
假设我声明了一个类C,其中一些声明非常相似。我想使用函数f 来减少这些声明的代码重复。可以像往常一样声明和使用f:
>>> class C(object):
... def f(num):
... return '<' + str(num) + '>'
... v = f(9)
... w = f(42)
...
>>> C.v
'<9>'
>>> C.w
'<42>'
>>> C.f(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method f() must be called with C instance as first argument (got int instance instead)
哎呀!我无意中将f 暴露给了外界,但它不需要self 参数(并且不能出于明显的原因)。一种可能性是在我使用该功能后del:
>>> class C(object):
... def f(num):
... return '<' + str(num) + '>'
... v = f(9)
... del f
...
>>> C.v
'<9>'
>>> C.f
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'C' has no attribute 'f'
但是如果我想在声明之后再次使用f 怎么办?删除该功能是不行的。我可以将其设为“私有”(即在其名称前加上 __)并对其进行 @staticmethod 处理,但通过异常通道调用 staticmethod 对象会变得非常时髦:
>>> class C(object):
... @staticmethod
... def __f(num):
... return '<' + str(num) + '>'
... v = __f.__get__(1)(9) # argument to __get__ is ignored...
...
>>> C.v
'<9>'
我必须使用上面的疯狂,因为staticmethod 对象,它们是描述符,它们本身是不可调用的。我需要恢复被staticmethod 对象包裹的函数,然后才能调用它。
必须有更好的方法来做到这一点。如何在类中干净地声明一个函数,在其声明期间使用它,并稍后在类中使用它?我应该这样做吗?
【问题讨论】:
标签: python class declaration static-methods invocation