距离高考倒计时还有五天,唔。。。高考加油
高考,人生的转折点,考好了继续奋斗,考不好回家继承…
子类继承父类,不仅可以单继承,还可以多继承,继承隔壁王叔叔家的…
好吧,进入今天主题:
一、继承
1.什么是继承
让子类直接拥有父类的属性和方法的过程就是继承
父类 - 被继承者(又叫超类)
子类 - 继承者
2.怎么继承
class 类名(父类1,父类2,…):
类的说明文档
类的内容
注意: 默认情况下,定义的类继承自 object
class Person:
num = 61
def __init__(self):
print('Person中init')
self.name = '小明'
self.age = 18
self.gender = '男'
self.__sex = '女'
def eat(self):
print(f'Person:{self.name}在吃饭')
@classmethod
def show_num(cls):
print(f'人类的数量:{cls.num}')
@staticmethod
def func1():
print('人类破坏环境!')
# 让 Student(子类) 继承 Person(父类)
class Student(Person):
pass
# 继承的时候子类可以直接拥有父类所有的属性和方法
print(Student.num)
stu = Student()
print(stu.name, stu.age, stu.gender)
stu.eat()
Student.show_num()
Student.func1()
print(stu.__dict__)
3.在子类中添加内容
1)在子类中添加类属性和方法
类属性和方法的添加不会因为继承而收到任何影响
2) 添加对象属性
对象属性是怎么被继承:继承的时候因为init方法被继承,间接继承了对象属性
在子类的__init__方法中通过 super()去调用父类的__init__方法
类中的方法的调用过程(重要)
通过类或者对象在调用方法的时候,会先看当前类中有没有这个方法,如果有就直接调用自己类中的方法;没有就看父类中有没有定义这个方法,如果父类定义了就调用父类的;父类没有定义,就看父类的父类中有没有定义…以此类推,如果 object 中没有定义才会报错!
class Teacher(Person):
title = '老师'
def __init__(self):
# 调用父类的init方法
super().__init__()
self.school = '千锋'
self.subject = 'Python'
self.tea_id = '001'
def attend_class(self):
print('老师上课')
def eat(self):
super().eat()
print(f'老师在吃饭')
print(Teacher.num, Teacher.title)
t1 = Teacher()
t1.attend_class()
print(t1.school, t1.subject, t1.tea_id)
print(t1.name)
t1.eat()
二、多继承
例:
class Animal:
num = 10
def __init__(self, age, gender):
self.age = age
self.gender = gender
def eat(self):
print('动物需要吃东西')
class Fly:
name = '飞行器'
def __init__(self, height, time):
self.height = height
self.time = time
def stop(self):
self.height = 0
print('停止飞行')
class Bird(Animal, Fly):
pass
b1 = Bird(2, '雌')
两个父类的类属性都可以继承
print(Bird.num)
print(Fly.name)
对象属性只会继承第一个父类的
print(b1.age, b1.gender)
# print(b1.height, b1.time) # AttributeError: 'Bird' object has no attribute 'height'
两个父类的不同方法都可以继承
b1.eat()
b1.stop()
super的用法
super(类, 对象) - 获取指定类的父类(对象必须是类的对象; 类默认指向当前类,对象默认是当前类的对象)
class A:
def show(self):
print('A')
pass
class B(A):
def show(self):
print('B')
class B2:
def show(self):
print('B2')
class C(B, B2):
def show(self):
# super().show() 等同于 ==> # super(C, self).show()
# 调用C的父类,如果super里面有值,则是调用值的父类,比如:
super(B, B()).show()
# 这里是调用B的父类,则是A,
print('C')
c = C()
c.show()
三、运算符重载
运算符重载
python中使用每一个运算符其本质都是在调用运算符对应的方法(每个运算符都会对应一个固定的方法)。
某种类型的数据支不支持某个运算符,就看这个数据对应的类型中有没有实现运算符对应的方法
简单来说,就是在你自己写的class里面,如果遇到运算符不支持你想要的运算(比如人属性做乘法,列表比大小等),你可以直接重写运算符的方法,以实现你自己需要的运算法则
(当然除了自己写的类之外,部分也可以实现,具体根据情况而定)
10 + 20 # 10.__add__(20)
'abc' + '123' # 'abc'.__add__('123')
100 - 10 # 100.__sub__(10)
dict
# {'a': 10} + {'b': 20}
class Person:
def __init__(self, name='', age=0):
self.name = name
self.age = age
# +
def __add__(self, other):
# self + other
return self.age + other.age
# *
def __mul__(self, other):
list1 = []
for _ in range(other):
list1.append(copy(self))
return list1
# <
# 注意:大于符号和小于符号实现其中一个另外一个也可以用
def __lt__(self, other):
return self.age < other.age
def __repr__(self):
return f'<{str(self.__dict__)[1:-1]}>'
p1 = Person('小明', age=18)
p2 = Person(age=30)
print(p1 == p2)
print(p1 + p2) # p1.__add__(p2)
# 10+20 -> 10.__add__(20)
# 10 * 2
print(p1 * 3) # []
persons = [Person('小花', 20), Person('Tom', 18), Person('张三', 28), Person('李四', 15)]
persons.sort()
print(persons)
# print(p1 > p2)
四、单例模式
1.单例类
class Person:
__obj = None
def __new__(cls, *args, **kwargs):
# print('new')
# new_obj = super().__new__(cls)
# print('new:', new_obj)
# return new_obj
if not cls.__obj:
cls.__obj = super().__new__(cls)
return cls.__obj
def __init__(self):
print('init:', self)
p1 = Person()
p2 = Person()
p3 = copy(p1)
print(p1 is p2)
print(p1 is p3)
"""
def Person(*args, **kwargs):
对象 = Person.__new__()
对象.__init__(*args, **kwargs)
return 对象
"""