<pre><code>def expand(self,expand):
return Rectangle(self.x - expand, self.y - expand, self.w + 2*expand,
self.h + 2*expand)
</code></pre>
<p>或者更通用的方法来防止未来的过载。。。。在</p>
^{pr2}$
<p>还有。。。。负维度呢?也许最好在构造函数中修复它:</p>
<pre><code>def __init__(self, initx, inity, initw, inith):
self.x = initx
self.y = inity
self.w = max(0,initw)
self.h = max(0,inith)
</code></pre>
<p>最后,我们可以讨论问题的主题:<em>似乎无法从我的类</em>获得输出。也许是缩进的问题,我会用我的方法重写你的脚本,并修复缩进问题。在</p>
<pre><code>class Rectangle:
def __init__(self, initx, inity, initw, inith):
self.x = initx
self.y = inity
self.w = max(0,initw)
self.h = max(0,inith)
def __str__(self):
return('Rectangle(' + str(self.x) + ',' + str(self.y) + ','
+ str(self.w) + ',' + str(self.h)+')')
def right(self):
return self.x + self.w
def top(self):
return self.y + self.h
def size(self):
return '(' + self.w + ',' + self.h+ ')'
def position(self):
return '(' + self.x + ',' + self.y + ')'
def area(self):
return self.w * self.h
def expand(self,expand):
return type(self)(self.x - expand, self.y - expand, self.w + 2*expand,
self.h + 2*expand)
r = Rectangle(5,10,50,100)
r2 = Rectangle(5,10,50,100)
r3 = Rectangle(3,5,10,20)
r4 = Rectangle(12,10,72,35)
r5 = Rectangle(5,7,10,6)
r6 = Rectangle(1,2,3,4)
print(r2)
print(r3.right())
print(r4.right())
print(r5.top())
print(r6.size())
print(r6.position())
print(r6.area())
</code></pre>
<p>现在它应该像你期望的那样工作。在代码中,您在类定义中放置了变量定义和<code>print</code>语句。在</p>