打印类实例

时间:2013-12-05 20:24:30

标签: python python-3.x

我正在尝试让以下类返回rectangle(x=5,y=10,width=50,and height=100),但我无法弄清楚为什么它不会在Python3和IDLE中返回它。我也试过print函数,但它也没有用:

class rectangle:

   def point(self):
     self.x = 5
     self.y = 10
     self.width = 50
     self.height = 100
     return("rectangle"(self.x,self.y,self.width,self.height))

2 个答案:

答案 0 :(得分:2)

要在Python中打印对象,您应该定义__str__方法:

class rectangle:

   def __init__(self, x=0, y=0, width=0, height=0):
       self.x = x
       self.y = y
       self.width = width
       self.height = height

   def __str__(self):
       return "rectangle (x=%s, y=%s, width=%s, height=%s)" % (self.x, 
                                                               self.y, 
                                                               self.width, 
                                                               self.height)

r = rectangle(5, 10, 50, 100)
print r

输出:

rectangle (x=5, y=10, width=50, height=100)

答案 1 :(得分:1)

您正在尝试将字符串视为可调用字符串。如果要返回的新实例,请调用类:

class rectangle:
     def __init__(self, x, y, width, height):
         self.x = x
         self.y = y
         self.width = width
         self.height = height

     def point(self):
         self.x = 5
         self.y = 10
         self.width = 50
         self.height = 100
         return rectangle(self.x, self.y, self.width, self.height)

请注意,这确实要求您的班级有__init__方法!

如果你想返回一个字符串,你必须使用字符串格式:

return "rectangle({}, {}, {}, {})".format(self.x, self.y, self.width, self.height)