<p>方法链接只是能够将<code>.second_func()</code>添加到任何返回的<code>.first_func()</code>中。通过确保所有可链接的方法都返回<code>self</code>,它相当容易实现。(注意,这与<code>__call()__</code>无关)。</p>
<pre><code>class foo():
def __init__(self, kind=None):
self.kind = kind
def my_print(self):
print (self.kind)
return self
def line(self):
self.kind = 'line'
return self
def bar(self):
self.kind='bar'
return self
</code></pre>
<p>您可以通过忽略返回值以非链接方式使用<code>foo</code>对象:</p>
<pre><code>a = foo()
a.line()
a.my_print()
a.bar()
a.my_print()
assert a.kind == 'bar'
</code></pre>
<p>或者,因为每个函数现在都返回对象本身,所以可以操作
直接返回值。可以将方法链接与此等效代码一起使用:</p>
<pre><code>b = foo()
b.line().my_print().bar().my_print()
assert b.kind == 'bar'
</code></pre>
<p>甚至:</p>
<pre><code>c = foo().line().my_print().bar().my_print()
assert c.kind == 'bar'
</code></pre>
<p>摆脱<code>()</code>调用语法的问题是一个完全独立于方法链的概念</em>。如果您想要链属性,并让这些属性改变其对象,请使用<code>@property</code>装饰器。(但是通过一个属性改变对象似乎是危险的。例如,最好使用一个方法并用动词命名:<code>.set_line()</code>,而不是<code>.line</code>。)</p>
<pre><code>class foo():
def __init__(self, kind=None):
self.kind = kind
def my_print(self):
print (self.kind)
return self
@property
def line(self):
self.kind = 'line'
return self
@property
def bar(self):
self.kind='bar'
return self
a = foo()
a.line
a.my_print()
a.bar
a.my_print()
assert a.kind == 'bar'
b = foo()
b.line.my_print().bar.my_print()
assert b.kind == 'bar'
c = foo().line.my_print().bar.my_print()
assert c.kind == 'bar'
</code></pre>