I'm new to Python. Let's say that I have a Parent base class and a derived Child class that inherits from Parent:
class Parent():
def foo(self):
print('foo in Parent')
def bar(self):
print('bar in Parent')
class Child(Parent):
pass
print(Child.__dict__)
print(Parent.__dict__)
The output is something like this:
# Child.__dict__
{'__module__': '__main__', '__doc__': None}
# Parent.__dict__
{'__module__': '__main__', 'foo': <function Parent.foo at 0x104f76680>, 'bar': <function Parent.bar at 0x104f76710>, '__dict__': <attribute '__dict__' of 'Parent' objects>, '__weakref__': <attribute '__weakref__' of 'Parent' objects>, '__doc__': None}
My understanding is that foo and bar in Parent class are instance methods so they don't appear in Child.__dict__. This is how it works in order for Child class to be able to override those methods, please correct me if I'm wrong.
If i change Child class a little bit, by creating an alias named foo and assign it to method foo in Parent class:
class Child(Parent):
foo = Parent.foo
I expect this to not work because Child already inherits all the members that Parent so it doesn't make sense that I can create another foo when one already exists.
But it works, if I create an object of type Child and call foo from it, it will print foo in Parent. And contents of Child.__dict__ and Parent.__dict__ now are:
Child.__dict__
{'__module__': '__main__', 'foo': <function Parent.foo at 0x1010ee680>, '__doc__': None}
Parent.__dict__
{'__module__': '__main__', 'foo': <function Parent.foo at 0x1010ee680>, 'bar': <function Parent.bar at 0x1010ee710>, '__dict__': <attribute '__dict__' of 'Parent' objects>, '__weakref__': <attribute '__weakref__' of 'Parent' objects>, '__doc__': None}
With foo method now in Child.__dict__ at the same address of 0x1010ee680.
Can someone walk me through what's going on here and is this something that one should do/avoid? Thank you!