adr*_*ian 4 python static-methods class declaration invocation
假设我正在声明一个类,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)
Run Code Online (Sandbox Code Playgroud)
哎呀!我无意中暴露在外面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'
Run Code Online (Sandbox Code Playgroud)
但是如果我想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>'
Run Code Online (Sandbox Code Playgroud)
我必须使用上面的疯狂,因为staticmethod作为描述符的对象本身不可调用.我需要恢复staticmethod对象包装的函数才能调用它.
必须有一个更好的方法来做到这一点.如何在类中干净地声明一个函数,在声明过程中使用它,以及稍后在类中使用它?我应该这样做吗?
Ali*_*har 14
很简单,解决方案是f不需要成为类的成员.我假设你的思维过程经历了一个导致心理障碍的Javaish语言过滤器.它有点像这样:
def f(n):
return '<' + str(num) + '>'
class C(object):
v = f(9)
w = f(42)
Run Code Online (Sandbox Code Playgroud)
然后当你想再次使用f时,只需使用它
>>> f(4)
'<4>'
Run Code Online (Sandbox Code Playgroud)
我想这个故事的寓意是"在Python,你不要有强迫一切都变成一个类".