Python 类方法(@classmethod) 使用:继承类信息
当子类需要在继承的类方法中使用继承的类信息时,可以使用 @classmethod 装饰器。
举个例子,假设我们有一个基类 Shape,它定义了一个类方法 get_info(),用于打印出图形的类型和颜色。我们还有两个子类 Circle 和 Rectangle,它们分别继承了基类 Shape。子类中的 get_info() 方法可以通过 @classmethod 装饰器获取继承的类信息。
代码示例:
class Shape:
color = 'unknown'
@classmethod
def get_info(cls):
print('This is a', cls.__name__, 'with color', cls.color)
class Circle(Shape):
radius = 5
color = 'red'
class Rectangle(Shape):
width = 10
height = 6
color = 'blue'
Circle.get_info() # 输出: This is a Circle with color red
Rectangle.get_info() # 输出: This is a Rectangle with color blue
在上面的示例中,Shape 类定义了一个类方法 get_info(),它使用 @classmethod 装饰器。子类 Circle 和 Rectangle 分别继承了基类 Shape,并覆盖了 color 属性。
通过调用类方法 get_info(),子类可以访问继承的类信息并打印出相应的信息。在这个例子中,子类 Circle 和 Rectangle 分别打印出自己的类型和颜色。
这是一个示例,说明了当子类需要在继承的类方法中使用继承的类信息时,可以使用 @classmethod 装饰器。
原文地址: https://www.cveoy.top/t/topic/i5K 著作权归作者所有。请勿转载和采集!