我是“类”方法的新手,如果有人感到不满,对不起。每个人都知道这个例子:
class Rectangle:
def __init__(self, length, breadth, unit_cost=0):
self.length = length
self.breadth = breadth
self.unit_cost = unit_cost
def get_perimeter(self):
return 2 * (self.length + self.breadth)
def get_area(self):
return self.length * self.breadth
def calculate_cost(self):
area = self.get_area()
return area * self.unit_cost
现在要获取信息,我们需要执行以下操作:
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s cm^2" % (r.get_area()))
print("Cost of rectangular field: Rs. %s " %(r.calculate_cost()))
结果:
但是我不这样做,我需要这样写:
Rectangle(160, 120, 2000)
并立即获得答案:
我可以使用普通的def我的函数:但是我想按班做。谢谢你的帮助!
使用__repr__
使类的可打印表示,然后从内添加一个print语句__init__
,如果你想避免使用类的打印之外(你可以让此可选)。
class Rectangle:
def __init__(self, length, breadth, unit_cost=0):
self.length = length
self.breadth = breadth
self.unit_cost = unit_cost
print(self)
def __repr__(self):
area_str = "Area of Rectangle: %s cm^2" % (self.get_area())
cost_str = "Cost of rectangular field: Rs. %s " %(self.calculate_cost())
return area_str + "\n" + cost_str
def get_perimeter(self):
return 2 * (self.length + self.breadth)
def get_area(self):
return self.length * self.breadth
def calculate_cost(self):
area = self.get_area()
return area * self.unit_cost
输出:
r =矩形(160,120,2000)
Area of Rectangle: 19200 cm^2
Cost of rectangular field: Rs. 38400000
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句