Python method/function chaining

拈花ヽ惹草 提交于 2020-03-23 04:22:25

问题


In python, is it possible to chain together class methods and functions together? For example, if I want to instantiate a class object and call a method on it that affects an instance variable's state, could I do that? Here is an example:

class Test(object):
    def __init__(self):
        self.x = 'Hello'

    @classmethod
    def make_upper(y):
        y.x = y.x.upper()

What I'm wanting to do is this:

h = Test().make_upper()

I want to instantiate a class object and affect the state of a variable in one line of code, but I would also like to be able to chain together multiple functions that can affect state or do something else on the object. Is this possible in python like it is in jQuery?


回答1:


Yes, sure. Just return self from the instance methods you are interested in:

class Test(object):
    def __init__(self):
        self.x = 'Hello'

    def make_upper(self):
        self.x = self.x.upper()
        return self
    def make_lower(self):
        self.x = self.x.lower()
        return self

h = Test().make_upper()
print(h.x)

Output:

HELLO



回答2:


Yes and no. The chaining certainly works, but h is the return value of make_upper(), not the object returned by Test(). You need to write this as two lines.

h = Test()
h.make_upper()

However, PEP-572 was recently accepted for inclusion in Python 3.8, which means someday you could write

(h := Test()).make_upper()

The return value of Test() is assigned to h in the current scope and used as the value of the := expression, which then invokes its make_upper method. I'm not sure I would recommend using := in this case, though; the currently required syntax is much more readable.



来源:https://stackoverflow.com/questions/51176274/python-method-function-chaining

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!