简体   繁体   中英

python figure which properties belong to the child class

I have a python class hierarchy as follows:

class A:
    def __init__(self):
        self.a = 1
        self.b = 2

class B(A):
    def __init__(self):
        super(B, self).__init__()
        self.c = 3

Now when I do something like:

obj = B()
obj.__dict__

I get:

{'a': 1, 'b': 2, 'c': 3}

is it possible to identify which of these properties belong to the parent class or rather which of these properties are of the child only?

For your simple example, you could get the difference in the dict items:

print(obj.__dict__.items() - A().__dict__.items())

I suppose we should at least to it without knowing the name of the parent class:

 print(obj.__dict__.items() - obj.__class__.__bases__[0]().__dict__.items())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM