has a 关系
- has a:一个类中使用了另外一种自定义的类型
- 类型:
系统类型 | int、float 、str、list、tuple、set、dict |
---|---|
自定义类型 | 使用 class 关键字自定义的类,类实例化的对象为自定义类型的对象 |
is a 关系
- is a:子类继承父类(基类)
- 如果子类中不定义 __init__,调用父类 super class 的 __init__
- 如果子类继承父类也需要定义自己的 __init__,就需要在当前类的 __init__ 中调用一下父类的 __init__
- 如何调用父类 __init__:
- super().__init__(参数)
- super(类名,对象).__init__(参数)
- 如果子类跟父类中有着相同的方法,默认调用的原则:先找当前类,再去找父类
- override:重写(覆盖):父类提供的方法不能满足子类的需求,就需要在子类中定义一个同名的方法
- 子类的方法中也可以调用父类方法:
- super().方法名(参数)
代码示例:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print('{}正在吃宫保鸡丁'.format(self.name))
class Student(Person):
def __init__(self, name, age, class_):
super(Student, self).__init__(name, age)
self.class_ = class_
def eat(self):
print('{}正在吃剁椒鱼头'.format(self.name))
def __str__(self):
return '我叫{0},今年{1}岁,是{2}的学生'.format(self.name, self.age, self.class_)
class Employee(Person):
def __init__(self, name, age, salary):
super(Employee, self).__init__(name, age)
self.salary = salary
def eat(self):
super().eat()
print('{}正在吃麻辣鸡丝'.format(self.name))
def myDaughter(self, son):
print('我的女儿{}在上学'.format(son.name))
def __str__(self):
return '我叫{},今年{}岁,每个月的工资是{}元'.format(self.name, self.age, self.salary)
s = Student('lucy', 18, '1班')
print(s)
s.eat()
e = Employee('Jack', 30, 10000)
print(e)
e.eat()
# 传入学生类型的对象
e.myDaughter(s)
# 运行结果:
我叫lucy,今年18岁,是1班的学生
lucy正在吃剁椒鱼头
我叫Jack,今年30岁,每个月的工资是10000元
Jack正在吃宫保鸡丁
Jack正在吃麻辣鸡丝
我的女儿lucy在上学