简体   繁体   English

在 Python 中的类中实现方法链

[英]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/ .我正在阅读在 Python 中使用 Fluent 接口的文档并遇到了这个包: https : //pypi.org/project/fluentpy/

I created a rather contrived example to test this like the below Persons class :我创建了一个相当人为的示例来测试它,如下面的 Persons 类:

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 .正如我们所见,方法get_lengthsget_name_length_map可以链接。

Below is a simple example of how we use this class in the simple case(without using fluentpy):下面是一个简单的例子,说明我们如何在简单的情况下使用这个类(不使用 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 ?有人可以指出我可以在这里使用 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.在每个可链接的方法之后返回self 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 ;当函数不返回除null|undefined|None之外的任意值时,使用可Chainable methods for example, if you had a function popItem , it could be chainable, but only if you did not return that popped value.例如,如果您有一个函数popItem ,它可以是可链接的,但前提是您没有返回该popped值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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