3

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 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I have to remember the id function from now on ^^ So, to extend my question if you don't mind: what happens when an instance of ListWithLoadMethod calls list.extend? Does list.extend(iterable) actually look like list.extend(self, iterable) when in use or what?
When you call list.extend on instance of ListWithLoadMethod below happens: 1) l_obj = ListWithLoadMethod() 2) ListWithLoadMethod.extend(l_obj, iterable). So it works similar other class methods
Thanks again! You've been a great help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.