rpadovani rpadovani - 1 year ago 51
Python Question

Python - method of a class with an optional argument and default value a class member

I have something like this (I know this code doesn't work, but it's the closer to what I want to achieve):

class A:
def __init__(self):
self.a = 'a'

def method(self, a=self.a):
print a

myClass = A()

myClass.method('b') # print b
myClass.method() # print a


What I've done so far, but I do not like it, is:

class A:
def __init__(self):
self.a = 'a'

def method(self, a=None):
if a is None:
a = self.a

print a

myClass = A()

myClass.method('b') # print b
myClass.method() # print a

Answer Source

Default arguments are evaluated at definition time. By the time the class and method are defined self.a is not.

Your working code example is actually the only clean way of achieving this behavior.