首页 > 解决方案 > Using inherited variables in subclass's method on their default arguments

问题描述

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

标签: pythonpython-3.xclassoopinheritance

解决方案


您不能真正在函数参数中获得继承self的属性,因为没有在那里定义。您可以从@MarkTolonen 显示的父级中获取类属性。这可能是你想要的,但它不是一回事。

考虑:

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

如果答案仍然是,someval那么这就是您所需要的,但如果您希望答案是other,那么这不起作用。您将需要使用设置默认值的模式实际设置函数体中的值None并检查:

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

推荐阅读