我正在自学Python类和子类。我试图在书中提一个问题,但被卡住了。我正在尝试创建3个三角形和4个正方形,并打印出一个三角形和一个正方形的所有属性,但是我不确定如何。谢谢您的帮助! 。这本书给了我这个:
> class Shape(object):
> def __init__(self, corner=10):
> self.__corner= corner
> self.__sides=corner
这是我到目前为止所拥有的:
class Shape(object): def __init__(self, corner=10): self.__corner= corner self.__sides=corner def set_corner(self, corner): self.__corner= corner def set_sides(self, corner): self.__sides= corner def get_corner(self): return self.__corner def get_sides(self): return self.__sides class Square(Shape): def __init__(self, corner, area): Shape.__init__(self, corner=10) self.__area=area def set_area(self,area): self.__area= area def get_area(self,area): return self.__area class Triangle(Shape): def __init__(self, corner, height): Shape.__init__(self, corner=10) self.__height=height def set_height(self,height): self.__height= height def get_height(self,height): return self.__height
答案 0 :(得分:0)
使用您的代码(只需最少的修改),这是一种实现方式:
class Square(Shape):
def __init__(self, corner, area):
Shape.__init__(self, corner = 10)
self.__area = area
def set_area(self):
self.__area = area
def get_area(self):
return self.__area
class Triangle(Shape):
def __init__(self, corner, height):
Shape.__init__(self, corner = 10)
self.__height = height
def set_height(self):
self.__height = height
def get_height(self):
return self.__height
# example triangle
t1 = Triangle(3, 50)
# example square
s1 = Square(5, 20)
# print the attributes
print('Triangle 1 height: {height} units.'.format(height=t1.get_height()))
print('Square 1 area: {area} sq. units.'.format(area=s1.get_area()))
打印:
Triangle 1 height: 50 units.
Square 1 area: 20 sq. units.
可能需要调整值以获得合理的结果。