Using superclass methods as instance methods

87 Views Asked by At

I am currently reading through Luciano Ramalho's excellent book Fluent Python. In a chapter about interfaces and inheritance we build a subclass of a list (see github for the original code) and I am confused about the way we define one of the instance methods. For a simlified example my confusion is caused by a situation as follows:

class ListWithLoadMethod(list):
    load = list.extend

which generates a new subclass of list which has an alias for the extend method as load. We can test the class by writing

loaded_list = ListWithLoadMethod(range(4))
print(loaded_list)
loaded_list.extend(range(3))
print(loaded_list)
loaded_list.load(range(3))
print(loaded_list) 

which produces, as expected:

[0, 1, 2, 3]
[0, 1, 2, 3, 0, 1, 2]
[0, 1, 2, 3, 0, 1, 2, 0, 1, 2]

My confusion arises from on the difference of class methods and static methods. When the new instance of ListWithLoadedMethod is created, it is a subclass of list, but when we initialize the instance we point load to list.extend; how does Python know that by list.extend we do not mean that load should point to a class method of the list class but to actually (apparently?) inherit the instance method of the superclass list?

1

There are 1 best solutions below

3
On BEST ANSWER

It's actually not inheriting from superclass (list), but creating reference to list.extend method

When you inspect their identity, you will see that they are same objects in memory.

id(list.extend)
Out: 3102044666032

id(ListWithLoadMethod.load)
Out: 3102044666032