1

I would like to check whether the Child class defined classattr (which might be also defined in its parent class). This is a MWE:

class Base(object):
    classattr=1
class Child(Base):
    pass

print(hasattr(Child,'classattr'))

which prints True. The same happens using inspect.getmebers.

How can I find out in which class was the class attribute defined?

eudoxos
  • 17,885
  • 10
  • 56
  • 100

1 Answers1

4

Check if the __dict__ has a key classattr

'classattr' in Child.__dict__
False
'classattr' in Base.__dict__
True
Lior Cohen
  • 5,227
  • 1
  • 13
  • 28
  • There exists an equivalent: `'classattr' in vars(Child)` See: https://stackoverflow.com/questions/21297203/use-dict-or-vars – VPfB Jan 01 '21 at 13:56