|
本帖最后由 jackz007 于 2025-4-17 18:28 编辑
- class Shape:
- def __init__(self,name):
- self.name=name
- def area(self): # 缩进错误
- pass
- class Circle(Shape):
- def __init__(self, radius):
- super().__init__("圆形")
- self . radius = radius
- def area(self):
- return 3.14*self.radius*self.radius
-
- class Triangle(Shape):
- def __init__(self, base,height):
- super().__init__("三角形")
- self.base=base # 属性 base 写错了
- self.height=height
- def area(self):
- return self.base*self.height/2
- class Square(Shape):
- def __init__(self,length):
- super().__init__("正方形")
- self.length=length
- def area(self):
- return self.length*self.length
- s=Square(5)
- c=Circle(6)
- t=Triangle(3,4)
- print(s . name)
- print(s . length)
- print(s . area()) # area 是方法,不是属性
- print(c . name)
- print(c . radius)
- print(c . area()) # area 是方法,不是属性
- print(t . name)
- print(t . base)
- print(t . height)
- print(t . area()) # area 是方法,不是属性
复制代码
添加 __repr__() 方法可以直接打印对象获取信息
- class Shape:
- def __init__(self,name):
- self.name=name
- def area(self):
- pass
- class Circle(Shape):
- def __init__(self, radius):
- super().__init__("圆形")
- self . radius = radius
- def area(self):
- return 3.14*self.radius*self.radius
- def __repr__(self):
- return f'shape : {self . name} , radius : {self . radius} , area : {3.14 * self . radius * self . radius}'
-
- class Triangle(Shape):
- def __init__(self, base,height):
- super().__init__("三角形")
- self.base=base
- self.height=height
- def area(self):
- return self.base*self.height/2
- def __repr__(self):
- return f'shape : {self . name} , base : {self . base} , height : {self . height} , area : {self . base * self . height / 2}'
- class Square(Shape):
- def __init__(self,length):
- super().__init__("正方形")
- self.length=length
- def area(self):
- return self.length*self.length
- def __repr__(self):
- return f'shape : {self . name} , length : {self . length} , area : {self . length * self . length}'
- s=Square(5)
- c=Circle(6)
- t=Triangle(3,4)
- print(s)
- print(c)
- print(t)
复制代码
运行实况:
- D:\[exercise]\Python>python x.py
- shape : 正方形 , length : 5 , area : 25
- shape : 圆形 , radius : 6 , area : 113.03999999999999
- shape : 三角形 , base : 3 , height : 4 , area : 6.0
- D:\[exercise]\Python>
复制代码 |
|