python - 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
解决方案
您不能真正在函数参数中获得继承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
推荐阅读
- matlab - Matlab:在箭袋图中绘制流线
- silverlight - MacOS Catalina 上的 Silverlight
- r - gganimate:结合 transition_layers 和 geom_smooth
- java - 有没有办法在关闭时使用 ContextListener 在 contextDestroyed() 方法中关闭所有 ThreadLocals(保存 Session 对象)?
- python - 如何在 Locust 中设置失败?
- java - Gradle build failed for Received status code 407 from server: Proxy Authentication Required, but another project's with similar deps Success
- wpf - 实体框架上下文未在 where 子句之间清除
- c# - 逗号分隔字母子集的 C# 正则表达式
- gmail-api - 如何在 javascript 中运行 gmail api 示例?
- arrays - Javascript循环遍历对象