mightyMouse
mightyMouse

Reputation: 738

classes and inheritance in python3

class Myclass(list):

    def remove_max(self):
        self.remove(max(self))

l = [1,2,3]

object = Myclass(l)

object.remove_max()

print(object)

in Myclass which inherits from class list why does the Myclass(l) assign the object a value [1,2,3]? And even if we gave it a string say 'abc' instead of list l as an input why is the value of object set as the list ['a'. 'b']?

Upvotes: 0

Views: 39

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 149185

As you do not define an __init__ method, the parameter given at construction time is given to the immediate parent, here list. And when you build a list from an iterable, you get the list composed from the different items. So:

  • if l is a list list(l) is a copy of the initial list
  • if s is a string (which is an iterable of characters), list(s) is the list composed with the characters from s

Upvotes: 1

Related Questions