【问题标题】:Need return to match what print is showing me需要返回以匹配打印显示的内容
【发布时间】:2016-10-31 01:29:15
【问题描述】:

我需要返回来给出最后一行打印的内容。 在底部,我用值调用了类。另外,欢迎指点改进代码。

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()

【问题讨论】:

  • 你会得到什么?请注意,str.format 更现代,您可能应该使用%r 来获取参数的表示形式。
  • 这与其他一些更改一起提供了帮助。现在我有一个不同的问题。 ://
  • 是的,欢迎来到编程。只要解决每一个小问题,最终就不会有任何问题。

标签: python python-3.x return repr


【解决方案1】:

改用__str__

    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
    ...

【讨论】:

  • 当测试用例只传递 4 个参数时,我需要指定它。当他们通过所有 5 时,我希望高度假设为第 5 个值。否则默认为 10。这就是我现在遇到的问题。
  • 在您的构造函数参数中包含height=10 正是这样做的。您不需要在构造函数中将其显式设置为 10。而且我注意到由于某种原因您正在初始化self.height 两次。只需保留第一个 self.height = height 并删除 self.height = 10。这应该会给你你正在寻找的行为。
  • 另外,如果解决方案对您有用,请记住将此答案标记为正确。 :)
猜你喜欢
  • 2014-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 2011-08-15
  • 1970-01-01
  • 2012-08-21
  • 1970-01-01
相关资源
最近更新 更多