David Lopez
David Lopez

Reputation: 1

Call self.variable(established in __init__() ) within class definition parameters

I would like to call a class variable established in init from a class definition so it can be the default parameter value. Wording is hard but here is an example.

class Sound:
   def __init__(self):
      self.volume = 10

   def set_volume(self, vol=self.volume)
      play_sound_a(vol)

I assumed that since init is called, then I should be able to use variables established in init from class definitions. I could do some if statements within the definition but using parameter defaults would be easier.

I simply get an error that self does not exist.

Upvotes: 0

Views: 30

Answers (1)

tdelaney
tdelaney

Reputation: 77347

It can't be done this way. The default parameter is defined when the method is compiled, well before any instance has been created. In fact, all instances of that class will share that same default value for that method. Instead you can use a sentinel such as None to know when you should use the instance volume. Assuming None is not otherwise a valid value for that parameter.

class Sound:
    def __init__(self):
        self.volume = 10

    def set_volume(self, vol=None):
        if vol is None:
            vol = self.volumne
        play_sound_a(vol)

Upvotes: 1

Related Questions