python--继承

39 阅读1分钟

python 继承:

(一)代码如下:

# 8.7.1 单继承 ++++++++++++++
class Cat:
    def __init__(self, color):
        self.color = color

    def walk(self):
        print("走猫步~")

# 定义 继承Cat的ScottishFold类
class ScottishFold(Cat):
    pass

fold = ScottishFold("灰色")  # 创建子类的对象
print(f"{fold.color}的折耳猫")  # 子类访问从父类继承的属性
fold.walk()  # 子类调用从父类继承的方法


# class Cat(object):
#
#     def __init__(self, color):
#         self.color = color
# #
#         self.__age = 1  # 增加私有属性
# #
#     def walk(self):
#         print("走猫步~")
# #
#     def __test(self):  # 增加私有方法
#         print("我是私有方法")
# #
# # 定义 继承Cat的ScottishFold类
# # class ScottishFold(Cat):

(二)运行结果如下:

image.png

题目: image.png

代码如下:

# 定义父类:矩形
class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    # 求周长
    def get_perimeter(self):
        return 2 * (self.length + self.width)

    # 求面积
    def get_area(self):
        return self.length * self.width


# 子类:长方形(直接继承矩形)
class RectangleSub(Rectangle):
    pass  # 无需额外代码,直接继承父类属性和方法


# 子类:正方形(继承矩形,强制长=宽)
class Square(Rectangle):
    def __init__(self, side):
        # 调用父类构造方法,保证长和宽相等
        super().__init__(side, side)


# 长方形实例
rect = RectangleSub(4, 6)
print("长方形周长:", rect.get_perimeter())  # 输出:20
print("长方形面积:", rect.get_area())      # 输出:24

# 正方形实例
square = Square(5)
print("正方形周长:", square.get_perimeter())  # 输出:20
print("正方形面积:", square.get_area())      # 输出:25

运行结果如下:

image.png