Access base class attribute in derived class - in “class scope”

风流意气都作罢 提交于 2019-11-29 11:52:37

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'}}
                  )

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.

πόδας ὠκύς

Python never searches for a name in enclosing class statements. Mark Lutz uses the acronym LEGB to summarize scope in his introduction to Python (Learning Python): Python searches the local scope, then the local scope of any enclosing def statements, then the global scope, and finally the built-in scope. Class statements are excluded from this scope list; Python does not search enclosing class statements for a name.

One solution is to un-nest your classes. In Python, using un-nested classes is often preferred for its simplicity. But, of course, there are good reasons to nest classes as well. Why have you nested InnerBase? I wonder if you might have nested that class because of your experience in Java. Would the following work for you just as well?

class InnerBase(object):
    _var = {'foo', 'bar'}

class Derived(InnerBase):
    _var = InnerBase._var | {'baz'}

>>> Derived._var
set(['baz', 'foo', 'bar'])

The moment you nest these two class statements under another class statement they will be excluded from name searches, since they have become part of the larger class statement and are thus excluded from the searching of the various scopes.

When you put it in a method it works.

    def __init__(self):
        _var = Outer.InnerBase._var | {'baz'}
        #_var = super(Outer.Derived, self)._var | {'baz'}    # or with super
        print(_var)

So my impression is that it's all about initialization.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!