Milo Wielondek
Milo Wielondek

Reputation: 4352

Make parent method return subclassed instance

Say I wish to subclass Python's set to change the difference method like so:

class my_set(set):
    def difference(self, ls):
        ls.append(1)
        return super().difference(ls)

Now assume I also added my_method to my_set and I wish to call it on the set resulting from calling difference:

my_instance = my_set([1,2,3])
my_instance.difference([2,3]).my_method()

The above won't work since the set returned from the difference method won't be of type my_set but of the regular set. What is the pythonic way of going around this without having to convert the returned set each time via my_set(my_instance.difference([2,3])).my_method()?

EDIT

I just realised I could wrap the return set like return my_set(super().difference(ls)). Haven't seen that before that, so not sure if this is the right way of achieving what I want. Care to comment?

Upvotes: 1

Views: 59

Answers (1)

Christian Tapia
Christian Tapia

Reputation: 34146

One thing you can do, is to create a my_set object from the result of super().difference(ls):

class my_set(set):
    def difference(self, ls):
        ls.append(1)
        return my_set(super().difference(ls)) # <---

    def my_method(self):
        print("StackOverflow")

my_instance = my_set([1,2,3])
my_instance.difference([2,3]).my_method() # CORRECT

Upvotes: 1

Related Questions