单继承
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())