I was working my way through a Python exercise when I started to play around and I came up with an interesting scenario and one way to solve it.
The main problem is that an inherited method from a superclass is called and is supposed to return an object of the same class as the current object instance, whether it's a subclass or the superclass.
I've created a list wrapper superclass with "-" overloaded. The method is supposed to return an object of the same class, so the operator can be used in a chain(newlist = mylist - 1 - 1). If I don't return the same class that comes in, then the overloaded operator won't work, as a list object doesn't have a __sub__ method
This is the base code with just the super class:
class mylist(object):
def __init__(self, list):
self.list = list[:]
def __sub__(self, other):
return mylist(self.list[:-other]) #------relevant part
def __str__(self):
return str(self.list)
Then I want to add a subclass with a trivial change, again overloading the "-" to mark how many times the operator is called and then calling the superclass "-" method. Once again I want to have the same class returned as that which is currently instantiated, otherwise the count won't be correct. The problem I kept coming up with is how to have the superclass create the subclass without knowing the which subclass is instantiated ahead of time. In the above code, the return explictly creates a mylist object which is returned.
The solution was to find a way to call the constructor through the self object. The __class__ method does exactly that. If I call self.__class__(...), then the new object is created which is returned.
The full code is below:
class mylist(object):
def __init__(self, list):
self.list = list[:]
def __sub__(self, other):
return self.__class__(self.list[:-other]) #----- relevant part
def __str__(self):
return str(self.list)
class mylistsub(mylist):
count = 0;
def __sub__(self, other):
mylistsub.count += 1
return mylist.__sub__(self, other)
alist = mylistsub([34,21,3432,12])
print alist - 1 - 1
print mylistsub.count # should be 2
Postscript
As a possibly more transparent alternative. you can do:
return type(self)(self.list[:-other])
Comments
quality writing skill
I am really impressed with your writing skills as well as with the layout on your blog. Is this a paid theme or did you customize it yourself? Either way keep up the nice quality writing, it is rare to see a nice blog like this one these days.
Post new comment