Python 需要返回以匹配打印显示的内容
我需要返回给最后一行打印的内容。 在底部,我用值调用了类。此外,还欢迎提出改进代码的建议Python 需要返回以匹配打印显示的内容,python,python-3.x,return,repr,Python,Python 3.x,Return,Repr,我需要返回给最后一行打印的内容。 在底部,我用值调用了类。此外,还欢迎提出改进代码的建议 class Building: def __init__(self, south, west, width_WE, width_NS, height=10): # making variables non-local self.south=int(south) self.west=int(west) self.width_WE=int(
class Building:
def __init__(self, south, west, width_WE, width_NS, height=10):
# making variables non-local
self.south=int(south)
self.west=int(west)
self.width_WE=int(width_WE)
self.width_NS=int(width_NS)
self.height=height
self.d={}
self.d['north-east']=(south+width_NS,west+width_WE)
self.d['south-east']=(south,west+width_WE)
self.d['south-west']=(south,west)
self.d['north-west']=(south+width_NS,west)
self.wwe=width_WE
self.wns=width_NS
self.height=10
def corner(self): # gives co-ordinates of the corners
print(self.d)
def area (self): # gives area
print(self.wwe*self.wns)
return(self.wwe*self.wns)
def volume(self): #gives volume
print(self.wwe*self.wns*self.height)
def __repr__(self): # I dont know what to call it but answer should be''Building(10, 10, 1, 2, 2)''
print ("Building(%s,%s,%s,%s,%s)"%(self.south, self.west, self.width_WE, self.width_NS,"10"))
#return ("Building(%s,%s,%s,%s,%s)"%(self.south, self.west, self.width_WE, self.width_NS,"10"))
abc = Building(10, 10, 1, 2, 2)
abc.corner()
abc.area()
abc.volume()
使用
\uuuu str\uuuu
代替:
def __str__(self):
return "Building({0},{1},{2},{3},{4})".format(self.south, self.west, self.width_WE, self.width_NS,"10")
def __repr__(self):
__str__()
另外,如果要将其作为参数传入,则可能不应显式设置height
:
...
self.height=10
...
应改为:
...
self.height=height
...
你得到了什么?请注意,
str.format
更为现代,您可能应该使用%r
来获取参数的表示形式。这与其他一些更改一起有所帮助。现在我有一个不同的问题/是的,欢迎收看节目。只要解决每一个小问题,最终就不会剩下任何问题。当测试用例只传递4个参数时,我需要指定它。当他们通过所有5,然后我想高度假设第五个值。否则默认为10。这就是我现在遇到的问题。在构造函数参数中设置height=10
正好可以做到这一点。您不需要在构造函数中显式地将其设置为10。我注意到,出于某种原因,您两次初始化了self.height
。只需保留第一个self.height=height
,然后删除self.height=10
。这应该会让你有你想要的行为。此外,如果解决方案对你有效,请记住将此答案标记为正确。:)