Chris
Chris

Reputation: 3509

Not Possible to Reference self in a Method Declaration?

I wanted to write a method with an argument that defaults to a member variable like so:

def method(self, arg1=0, arg2=self.member):

Apparently this is not allowed. Should I write it a different way, or perhaps use a value of arg2 to signal when to use the member variable?

Upvotes: 0

Views: 115

Answers (2)

Yaroslav
Yaroslav

Reputation: 2736

def method(self, arg1=0, arg2=None):
    if arg2 is None:
        arg2 = self.member
    ...

Upvotes: 2

Alex Martelli
Alex Martelli

Reputation: 881585

Yep, use a sentinel -- e.g.:

class Foo(object):
    _sentinel = object()
    def method(self, arg1=0, arg2=_sentinel):
        if arg2 is self._sentinel: arg2 = self.member
        ...
    ...

note that you need barename _sentinel in the def, but self._sentinel in the body of the method (since that's how scoping works out in class bodies vs method bodies;-).

Upvotes: 5

Related Questions