Reputation: 41
Is it possible to get the attribute of a child class in Python 3?
This doesn't work:
class Foo:
def __init__(self):
print(vars(self))
class Bar(Foo):
example_attribute = "baz"
test = Bar()
# prints {}
# I want it to print {"example_attribute": "baz"}
Upvotes: 2
Views: 48
Reputation: 2016
Something like the answer above but with a main to execute an instance of Bar()
class Foo:
def __init__(self):
print(vars(self.__class__))
class Bar(Foo):
example_attribute = "baz"
if __name__ == "__main__":
test = Bar()
Upvotes: 0
Reputation: 140148
your attribute is a class attribute. You can get it with:
class Foo:
def __init__(self):
print(vars(self.__class__))
result:
{'__module__': '__main__', 'example_attribute': 'baz', '__doc__': None}
if the attribute was an instance attribute, you would have to call the parent __init__
after you have defined it. Something like:
class Foo:
def __init__(self):
print(vars(self))
class Bar(Foo):
def __init__(self):
self.example_attribute = "baz"
Foo.__init__(self)
Upvotes: 3