Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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):
    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".

like image 744
PyNewbie Avatar asked Feb 15 '10 09:02

PyNewbie


2 Answers

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)

like image 197
Tim Dumol Avatar answered Sep 28 '22 04:09

Tim Dumol


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.

like image 35
kennytm Avatar answered Sep 28 '22 03:09

kennytm