设计一个圆柱体类,该类有通过参数初始化对象或通过一个已知对象初始化一个新对象,以及有求圆柱体体积和表面积的功能。
时间: 2024-05-29 09:11:53 浏览: 23
库伦摩擦力的MATLAB实现模型和使用示例
class Cylinder:
def __init__(self, radius=1, height=1):
self.radius = radius
self.height = height
def __repr__(self):
return f"Cylinder(radius={self.radius}, height={self.height})"
def volume(self):
return round(3.14 * self.radius ** 2 * self.height, 2)
def surface_area(self):
return round(2 * 3.14 * self.radius * self.height + 2 * 3.14 * self.radius ** 2, 2)
@classmethod
def from_cylinder(cls, cylinder):
return cls(cylinder.radius, cylinder.height)
# example usage
c1 = Cylinder(radius=2, height=5)
c2 = Cylinder.from_cylinder(c1)
print(c1) # Cylinder(radius=2, height=5)
print(c2) # Cylinder(radius=2, height=5)
print(c1.volume()) # 62.8
print(c2.volume()) # 62.8
print(c1.surface_area()) # 94.2
print(c2.surface_area()) # 94.2
阅读全文