I was working on a program in Python 2.7 and found myself attempting to pass a Python class field as a parameter within that same class. While I have modified my code to make it cleaner (and thereby eliminate the need for this construction), I am still curious.
For some examples (hugely simplified, but the concept is present):
[NB: For examples 1 and 2, suppose that I wanted to either take a number as input and increment it, or increment the current value.]
Example 1.
class Example:
def __init__(self,x):
self.value = x
def incr(self,x=self.value):
self.value = x + 1
Result:
"NameError: name 'self' is not defined"
Example 2.
class Example:
def __init__(self,x):
self.value = x
def incr(self,x=value):
self.value = x + 1
Result:
"NameError: name 'value' is not defined"
Example 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()
Result:
4
To restate my question, why can't I pass a Python class field as a parameter to its own method?
Let me know if you have any additional questions or would require more information. Thanks!