rpadovani
rpadovani

Reputation: 7360

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

Upvotes: 1

Views: 64

Answers (2)

Sven Marnach
Sven Marnach

Reputation: 601599

The default is evaluated at method definition time, i.e. when the interpreter executes the class body, which usually happens only once. Assigning a dynamic value as default can only happen within the method body, and the approach you use is perfectly fine.

Upvotes: 2

DeepSpace
DeepSpace

Reputation: 81594

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.

Upvotes: 3

Related Questions