为什么 Python 在每个参数列表中都需要一个显式的 self
参数?
例如在文档中给出的类 Complex
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
def conjugate(self):
self.i = -self.i
x = Complex(3.0, -4.5) # 2 instead of 3?
x.conjugate() # No parameters?
我最初发现它非常困惑,__init__( )
似乎需要 3
参数,但你调用 Complex( )
时只有 2 个参数。
self
参数是显式而不是隐式的原因是什么?
最佳答案
Here是 GvR 关于此事的一篇好文章。它讨论了为什么要保留显式 self
引用。
他提出的几点:
强化了
的等价性foo.meth(arg) == C.meth(foo, arg)
能够动态地将方法附加到一个类,然后可以从该类的所有新对象和已经存在的对象中使用:
def meth(myself, arg):
myself.val = arg
return myself.val
# Poke the method into the class:
C.meth = meth
我鼓励您阅读本文的其余部分。这很有趣。
关于python - 为什么 Python 会 self 显式化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11794918/