0

I would like to use an inherited variable as one of the default argument to a derived class's method. I want to do something that looks like the following :

class BaseFoo:
  _inherited = 'someval'

class Foo(BaseFoo):
  def dosomething( bar = _inherited ):
    print( bar ) # should print someval if we call dosomething()

I have tried using super()._inherited. But since super() needs an instance, putting it as a default arg will raise a RunTimeError: super() no arguments

I have also tried using self._inherited. But it returns a NameError, self not defined. I know that I can access _inherited within a function with either self or super(). But how do I do it on the while defining some default args ?

Edit : I am aware on how to access inherited attributes in subclasses. But This question focuses on using them as default arguments. For those looking on accessing the attributes may refer to Accessing attribute from parent class inside child class

1

2 Answers 2

4

You can't really get the inherited property in the function argument because self isn't defined there. You can get the class property off the parent which @MarkTolonen shows. This might be what you want, but it's not the same thing.

Consider:

class BaseFoo:
    _inherited = 'someval'

class Foo(BaseFoo):
    def someAction(self):
        self._inherited = "other"
    def dosomething(self,bar=BaseFoo._inherited ):
        print( bar, self._inherited ) # should print someval if we call dosomething()

f = Foo()
f.someAction()  # changes f._inherited to "other"
f.dosomething() # what should be printed? self._inherited or bar?
# prints someval other

If the answer is still someval then this does what you need, but if you are hoping that the answer is other, then this doesn't work. You will need to actually set the value in the function body using the pattern that sets the default to None and checks:

class BaseFoo:
    _inherited = 'someval'

class Foo(BaseFoo):
    def someAction(self):
        self._inherited = "other"
    def dosomething(self,bar=None):
        if bar is None:
            bar = self._inherited
        print( bar, self._inherited ) 

f = Foo()
f.someAction()
f.dosomething()
# prints other other
Sign up to request clarification or add additional context in comments.

Comments

1

You can refer to the base directly:

class BaseFoo:
  _inherited = 'someval'

class Foo(BaseFoo):
  def dosomething(self,bar=BaseFoo._inherited ):
    print( bar ) # should print someval if we call dosomething()

Output:

>>> f = Foo()
>>> f.dosomething()
someval

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.