在派生类中访问基类属性-在“类范围"中. [英] Access base class attribute in derived class - in "class scope"
问题描述
class Outer(object):
class InnerBase(object): _var = {'foo', 'bar'}
class Derived(InnerBase):
_var = _var | {'baz'} # NameError: name '_var' is not defined
_var = InnerBase._var | {'baz'} # name 'InnerBase' is not defined
_var = Outer.InnerBase._var | {'baz'} # free variable 'Outer'
# referenced before assignment in enclosing scope
在Outer
中移动_var无济于事-在模块范围内移动_var可以工作,但无法达到创建类的目的.那么如何解决呢?
Moving _var in Outer
does not help - moving it in module scope would work but defeats the purpose of having classes. So how to go about that ?
来自Java,所以类的作用域规则对我来说是一个头疼的问题-简要地介绍一下.顺便说一句:
coming from Java so the scoping rules of classes are a head scratcher for me - a briefing would be appreciated. This works btw:
class Derived(InnerBase): pass
Derived._var = InnerBase._var | {'baz'}
但这不是优雅的顶峰.
相关:嵌套类的作用域?-但是在这里,我们特别想访问父类类(而不是外部类型)
Related: Nested classes' scope? - but here we specifically want to access our parent class (rather than the Outer type)
我实际上所追求的是类似_var = __class__._var
的语法(或hack),或者是关于为什么不存在的解释
What I am actually after is a _var = __class__._var
-like syntax (or hack), or an explanation as to why it's not there
推荐答案
您可以绕过class
语句并使用对type
的显式调用.
You can bypass the class
statement and use an explicit call to type
.
class Outer(object):
class InnerBase(object): _var = {'foo', 'bar'}
Derived = type('Derived',
(InnerBase,),
{'_var': InnerBase._var | {'baz'}}
)
之所以可行,是因为未通过定义Derived
的class
语句中的赋值语句来设置Derived._var
,而是从您在与InnerBase
本身相同的环境中创建的字典中导入的.
This works because Derived._var
is not being set via an assignment statement in the class
statement defining Derived
, but is imported from a dictionary you create in the same environment as InnerBase
itself.
这篇关于在派生类中访问基类属性-在“类范围"中.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!