【问题标题】:Using inherited variables in subclass's method on their default arguments在子类的方法中使用继承变量的默认参数
【发布时间】:2019-10-08 13:27:34
【问题描述】:
我想使用继承变量作为派生类方法的 default 参数之一。我想做一些如下所示的事情:
class BaseFoo:
_inherited = 'someval'
class Foo(BaseFoo):
def dosomething( bar = _inherited ):
print( bar ) # should print someval if we call dosomething()
我尝试过使用 super()._inherited。但是由于 super() 需要一个实例,因此将其作为默认 arg 会引发 RunTimeError: super() no arguments
我也尝试过使用 self._inherited。但它返回一个 NameError,self 未定义。我知道我可以使用 self 或 super() 在函数中访问 _inherited。但是在定义一些默认参数时我该怎么做呢?
编辑:
我知道如何访问子类中的继承属性。但是这个问题的重点是使用它们作为默认参数。想要访问属性的朋友可以参考Accessing attribute from parent class inside child class
【问题讨论】:
标签:
python
python-3.x
class
oop
inheritance
【解决方案1】:
您无法真正在函数参数中获得 inherited 属性,因为self 没有在那里定义。您可以从 @MarkTolonen shows 的父级中获取类属性。这可能是你想要的,但不是一回事。
考虑:
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
【解决方案2】:
可以直接参考base:
class BaseFoo:
_inherited = 'someval'
class Foo(BaseFoo):
def dosomething(self,bar=BaseFoo._inherited ):
print( bar ) # should print someval if we call dosomething()
输出:
>>> f = Foo()
>>> f.dosomething()
someval