2

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!

David C
  • 7,204
  • 5
  • 46
  • 65
  • 2
    Possibly your issue? http://stackoverflow.com/questions/1802971/nameerror-name-self-is-not-defined – r36363 Aug 03 '12 at 22:18

1 Answers1

5

Method default values are evaluated when the method is defined, not when the method is called. At that point the class is still being defined, and so no objects of that type exist. Therefore you cannot use self.

You can use the workaround of having a default value of None and testing for this inside your method:

def incr(self,x=None):
    if x is None:
        x = self.value
    self.value = x + 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452