How does the super type present itself and do lookups?
Peter Otten
__peter__ at web.de
Tue Mar 10 10:27:42 EDT 2020
Adam Preble wrote:
> If you don't know, you can trap what super() returns some time and poke it
> with a stick. If you print it you'll be able to tell it's definitely
> unique: <super: <class 'Child'>, <Child object>>
>
> If you try to invoke methods on it, it'll invoke the superclass' methods.
> That's what is supposed to happen and basically what already happens when
> you do super().invoke_this_thing() anyways.
>
> Okay, so how is it doing the lookup for that? The child instance and the
> super types' __dict__ are the same. The contents pass an equality
> comparison and are the same if you print them.
I think the fundamental insight is that given
class A:
foo = "A"
class B(A):
foo = "B"
def super_foo(self): return super().foo
def my_foo(self): return self.foo
b = B()
b.foo = "inst"
print(b.super_foo()) # A
print(b.my_foo()) # inst
del b.foo
print(b.my_foo()) # B
del B.foo
print(b.my_foo()) # A
self.foo looks up the attribute in the instance, falls back to the class and
then works its way up to the parent class, whereas
super().foo bypasses both instance and class, and starts its lookup in the
parent class.
More information about the Python-list
mailing list