Extending base classes in Python Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Extending base classes in Python without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m trying to extend some “base” classes in Python:

class xlist (list):
    def len(self):
        return len(self)

    def add(self, *args):
        self.extend(args)
        return None


class xint (int):
    def add(self, value):
        self += value
        return self


x = xlist([1,2,3])
print x.len()   ## >>> 3 ok
print x         ## >>> [1,2,3] ok
x.add (4, 5, 6)
print x         ## >>> [1,2,3,4,5,6] ok

x = xint(10)
print x         ## >>> 10 ok
x.add (2)
print x         ## >>> 10  # Not ok (#1)

print type(x)         ## >>> <class '__main__.xint'> ok
x += 5
print type(x)         ## >>> <type 'int'>  # Not ok (#2)

It works fine in the list case because the append method modifies the object “in place”, without returning it. But in the int case, the add method doesn’t modify the value of the external x variable. I suppose that’s fine in the sense that self is a local variable in the add method of the class, but this is preventing me from modifying the initial value assigned to the instance of the class.

Is it possible to extend a class this way or should I define a class property with the base type and map all the needed methods to this property?

Answer

int is a value type, so each time you do an assignment, (e.g. both instances of += above), it doesn’t modify the object you have on the heap, but replaces the reference with one of the result of the right hand side of the assignment (i.e. an int)

list isn’t a value type, so it isn’t bound by the same rules.

this page has more details on the differences: The Python Language Reference – 3. Data model

IMO, yes, you should define a new class that keeps an int as an instance variable

We are here to answer your question about Extending base classes in Python - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji