Gaurang Shah
Gaurang Shah

Reputation: 12910

how to verify if variable exist in parent class in python

I have to add all the variables exist in parent class in one list in child class. However all the variables in the parent class is not mandatory.

Is there any way i can figure out if variable exist in parent class or not ??

Upvotes: 1

Views: 569

Answers (2)

HennyH
HennyH

Reputation: 7944

>>> class A(object):
...     pass
... 
>>> class B(A):
...     pass
... 
>>> B.__bases__
(<class '__main__.A'>,)
>>> getattr(B.__bases__[0],'x',False)
False

Or more comprehensivley:

class A(object):
    x = 5

class B(A):
    y = 6
    x = 7

print(getattr(B.__bases__[0],'y',False))
print(getattr(B.__bases__[0],'x',False))

Outputs

False
5
>>> 

So just check wether or not False is returned, if it is then you can conclude the attribute doesn't exist in the parent class.

Upvotes: 1

Gyom
Gyom

Reputation: 3920

If you know what attributes you're looking for, you can match them against dir(parent class)

Upvotes: 0

Related Questions