开发者

Python: How to access parent class object through derived class instance?

I'm sorry for my silly question, but... let's suppose I have these classes:

class A():
    msg = 'hehehe'

class B(A):
    msg = 'hohoho'

class C(B):
   开发者_C百科 pass

and an instance of B or C. How do I get the variable 'msg' from the parent's class object through this instance? I've tried this:

foo = B()
print super(foo.__class__).msg

but got the message: "TypeError: super() argument 1 must be type, not classobj".


You actually want to use

class A(object):
    ...
...
b = B()
bar = super(b.__class__, b)
print bar.msg

Base classes must be new-style classes (inherit from object)


If the class is single-inherited:

foo = B()
print foo.__class__.__bases__[0].msg
# 'hehehe'

If the class is multiple-inherited, the question makes no sense because there may be multiple classes defining the 'msg', and they could all be meaningful. You'd better provide the actual parent (i.e. A.msg). Alternatively you could iterate through all direct bases as described in @Felix's answer.


Not sure why you want to do this

>>> class A(object):
...     msg = 'hehehe'
... 
>>> class B(A):
...     msg = 'hohoho'
... 
>>> foo=B()
>>> foo.__class__.__mro__[1].msg
'hehehe'
>>> 


As msg is a class variable, you can just do:

print C.msg    # prints hohoho

If you overwrite the variable (as you do in class B), you have to find the right parent class. Remember that Python supports multiple inheritance.

But as you define the classes and you now that B inherits from A you can always do this:

class B(A):
    msg = 'hohoho'

    def get_parent_message(self):
       return A.msg

UPDATE:

The most reliable thing would be:

def get_parent_attribute(instance, attribute):
    for parent in instance.__class__.__bases__:
        if attribute in parent.__dict__:
             return parent.__dict__[attribute]

and then:

foo = B()
print get_parent_attribute(foo, 'msg')


Try with:

class A(object):
    msg = 'hehehe'

EDIT:

For the 'msg' attribute you would need:

foo = B()
bar = super(foo.__class__, foo)
print bar.msg


#for B() you can use __bases__
print foo.__class__.__bases__[0].msg

But this is not gonna be easy when there are multiple base classes and/or the depth of hierarchy is not one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜