简体   繁体   中英

Implement method chaining in a class in Python

I was going through the documentation of using Fluent interfaces in Python and came across this package : https://pypi.org/project/fluentpy/ .

I created a rather contrived example to test this like the below Persons class :

class Persons:
    def __init__(self, names):
        self.names = names
        
    def get_lengths(self):
        return [len(name) for name in self.names]
    
    def get_name_length_map(self, lengths):
        return {
            name: length
            for name, length in zip(self.names, lengths)
        }

As we can see that the methods get_lengths and get_name_length_map can be chained .

Below is a simple example of how we use this class in the simple case(without using fluentpy):

p = Persons(["Subhayan", "Ralf", "Thomas", "Leo"])

print(p.get_lengths())

print(p.get_name_length_map(p.get_lengths()))

Can someone please point me to a way in which i can do method chaining here using fluentpy ? Is there some change to the class that i have to do to make it work ?

Any help would be greatly appreciated.

Return self after every chainable method. However, I don't think any of your methods are worthy candidates because they actually return a value that may be used somewhere (a user may want to read this value, but instead, gets an object instead of a number, confusing). Chainable methods are used when the function doesn't return arbitrary values other than null|undefined|None ; for example, if you had a function popItem , it could be chainable, but only if you did not return that popped value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM