我正在使用 Python 2.7 编写程序,发现自己试图将 Python 类字段作为同一类中的参数传递。虽然我已经修改了我的代码以使其更简洁(从而消除了对这种构造的需要),但我仍然很好奇。
对于一些例子(大大简化,但概念是存在的):
[注意:对于示例 1 和 2,假设我想将一个数字作为输入并增加它,或者增加当前值。]
示例 1。
class Example:
def __init__(self,x):
self.value = x
def incr(self,x=self.value):
self.value = x + 1
结果:
"NameError: name 'self' is not defined"
示例 2。
class Example:
def __init__(self,x):
self.value = x
def incr(self,x=value):
self.value = x + 1
结果:
"NameError: name 'value' is not defined"
示例 3。
class Example:
def __init__(self,x):
ex2 = Example2()
self.value = ex2.incr(x)
def get_value(self):
return self.value
class Example2:
def __init__(self):
self.value = 0
def incr(self,x):
return x + 1
ex = Example(3)
print ex.get_value()
结果:
4
重申我的问题,为什么我不能将 Python 类字段作为参数传递给它自己的方法?
如果您有任何其他问题或需要更多信息,请告诉我。谢谢!