擅长:python、mysql、java
<p><code>the second one ends up thinking it is supposed to modify the return of the first one instead of the original class</code>。是的,这是正常的Python语法。返回<code>self</code>不会创建特殊语法。它只是确保返回的对象是正确的链接对象。在</p>
<p>您的初始化任务通常编码为</p>
<pre><code>class SomeBlock():
def __init__(self, hardness=None, opaque=False, blastResistance=None):
self.hardness = hardness
self.opaque = opaque
self.blastResistance = blastResistance
ablock = SomeBlock(hardness=0.5, opaque=True, blastResistance=2)
</code></pre>
<p>而且由于<code>Python</code>不需要访问属性的方法,所以您还可以编写</p>
^{pr2}$
<p>因此,如果一个方法确实返回<code>self</code>,则通常实现一个比设置属性更复杂的方法。在</p>
<p>更常见的是让方法返回同一类的新对象。例如,这是许多<code>numpy</code>数组方法中的典型方法。<code>A.dot(B)</code>返回新数组,即取<code>A</code>和<code>B</code>的点积的结果。<code>A.dot(B).dot(C)</code>看起来像链接,但只是对连续数组的一系列操作。在</p>