1

I am attempting to use an instance attribute as a default parameter. Unfortunately, python doesn't seem to recognize the "self" variable

class Example(object):

    def __init__(self, name):
        self.bar = ""

    def foo(self, param=self.bar):
        print self.bar

Why doesn't python allow the use of self in the method signature? Also, any tips on a smooth way to achieve a similar result without the use of self?

ElliotPenson
  • 354
  • 1
  • 10
  • 2
    Because instance does not exist by the moment when the method is created, so do not exist its attributes. – bereal Feb 09 '14 at 20:47

2 Answers2

2

self is a parameter to the function. So until you enter the function, you can't do self.something because there is no definition of self before the function is entered.

You could do the following:

class Example(object):
    def __init__(self, name):
        self.bar = name

    def foo(self, param=None):
        if param is None:
            param = self.bar
        # do stuff with param, which now defaults to self.bar
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
2

Two reasons. Firstly, because self is also a parameter, and therefore only exists within the method body itself, not in the function signature.

But secondly, and more importantly, function defaults are evaluated at the time they are defined, not when they are called. So this would refer to an instance that hasn't even been created yet.

The answer is to define the default is None and check for that value inside the method.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895