Python 类的继承 单继承 多继承 super call方法

单继承

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height


class Square(Rectangle):
    def __init__(self, width, height):
        if width == height:
            super().__init__(width, height)
        else:
            print("长宽不相等, 不是正方形")


print(Square(5, 5).area())

多继承

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"{self.name} {self.age}"


class Student(Person):
    def __init__(self, name, age, school):
        super().__init__(name, age)
        self.school = school

    def __str__(self):
        return f"{super().__str__()} {self.school}"


class FemaleStudent(Student, Person):
    def __init__(self, name, age, school, state):
        super().__init__(name, age, school)
        self.state = state

    def __str__(self):
        return f"{super().__str__()} {self.state}"


print(FemaleStudent("小红", 18, "北京", 170))

类的实例可以像函数一样调用吗? 否, 类实例不能直接调用, 需要实例化后才能调用, 并且需要定义__call__方法

class XiaoLi(FemaleStudent):
    def __init__(self, name, age, school, state, height):
        super().__init__(name, age, school, state)
        self.height = height

    def __call__(self, *args, **kwargs):
        return f"{self.name} {self.age} {self.school} {self.state} {self.height}"


xl = XiaoLi("小丽", 18, "北京", 50, 170)
print(xl())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值