Home > database >  How do I chain methods in classes?
How do I chain methods in classes?

Time:10-23

This is the task I need to complete:

Consider that you are interested in coloured shapes on paper. Write a class 'Shape'which has a hidden attribute of colour, an access method to get the colour (you may wish to have a default colour) and an modifier method to set the colour.

Try and make it so that you can chain your methods, e.g.

s = Shape()
s.set('Red').colour()
Output: Red

s.set('Yellow').set('Blue').colour()
Output: Yellow

I'm very new to python, and im lost. This is what I already have and it's probably really wrong. I would appreciate some help.

This is what I already have:

class Shape:
    def __init__(self, colour = None):
        self._colour = colour
        
    def colour(self):
        print(self._colour)
        
    def set(self, new_colour):
        self.new_colour = new_colour
        self._colour = new_colour
        
s = Shape()

but it doesn't seem to work the way the task wants it to. please help.

CodePudding user response:

If you return self in the set method this will work. This is because you are calling .set() on the shape class, and if .set() does not return the object it belongs to, you are calling .set() on nothing.

CodePudding user response:

Return self in the set() method

class Shape:
    def __init__(self, colour=None):
        self._colour = colour

    def colour(self):
        print(self._colour)


    def set(self, new_colour):
        self.new_colour = new_colour
        self._colour = new_colour
        return self

CodePudding user response:

You chain methods by having one method return an object that has the next method(s) of interest. Frequently, that's the self object - allowing the programmer to call another method on that class.

But method chaining happens all over the place because all return values are objects with methods. For instance,

s = " ABC "
s_lowered = s.strip().lower()

In your case

class Shape:
    def __init__(self, colour = None):
        self._colour = colour
        
    def colour(self):
        print(self._colour)
        return self
        
    def set(self, new_colour):
        self.new_colour = new_colour
        self._colour = new_colour
        return self

s = Shape()
s.set('Red').colour()
s.set('Yellow').set('Blue').colour()

s.set() returns an unnamed reference to the s object which is used for the next .colour() call. That call returned another unnamed reference to the same s object, but since you don't assign it to anything, python discards it.

  • Related