Basic method chaining

后端 未结 3 1294
暗喜
暗喜 2020-12-01 00:41

I found this method chaining in python, but even with it I couldn\'t understand method chaining in Python.

Here the goals are two: solve the coding problem and under

3条回答
  •  北海茫月
    2020-12-01 01:29

    ther's an another interesting way of achieving this

    class Foo:
        def __init__(self, kind=[]):
            self.kind = kind
    
        def __getattr__(self, attrs):
            self.attrs = attrs
            return Foo(self.kind + [attrs]) 
    
        def __call__(self):
            return self.kind[::-1][0]
    
    
    my_obj = Foo()
    print(my_obj.bar.line.bar.bar.line())
    

    with this code u don't have to pass .my_print() but one thing to note here is the Foo class will take anything as argument like if we try print(my_obj.bar.line.bar.bar.circle()) it will return circle.

    You can also edit this code to take the args while calling any function.

提交回复
热议问题