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

I apologize for my stupid question, but ... let's say I have these classes:

class A():
    msg = 'hehehe'

class B(A):
    msg = 'hohoho'

class C(B):
    pass

and instance B or C. How to get msg variable from parent class object through this instance? I tried this:

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

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

+3
source share
6 answers

If the class is unidirectional:

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

, , , "msg", . (.. A.msg). , @Felix.

+7

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

( object)

+14

,

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

:

class A(object):
    msg = 'hehehe'

EDIT:

"msg" :

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

msg - , :

print C.msg    # prints hohoho

( B), . , Python .

But since you define classes and now that you Binherit 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:

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')
+1
source
#for B() you can use __bases__
print foo.__class__.__bases__[0].msg

But it will not be easy when there are several base classes and / or the depth of the hierarchy is not one.

0
source

Source: https://habr.com/ru/post/1732827/


All Articles