# 1.继承与抽象
# 抽取老师和学生中相同的部分形成person类
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def say_hi(self):
print("name:%s,gender:%s,age:%s" % (self.name, self.gender, self.age))
class Teacher(Person): # 继承person类
def teaching(self):
print("老师教学生,写代码....")
t1 = Teacher("jack", "male", 20)
t1.say_hi()
class Student(Person):
pass
stu1 = Student("rose", "female", 18)
stu1.say_hi()
# 2.属性的查找顺序
# 对象自己的 - > 所在类中 -> 找父类 - >父类的父类 ->Object(到这一步时会报错,因为object存在与源代码之中,此时属性为空)
# type ctrl加右键查看它的源码你就明白了
# 3.派生与覆盖是继承
这两个是继承的两种情况
# 4.元素类型限制
"""
需求 实现一个能够限制元素类型的列表类
"""
class MyList(list):
def __init__(self,element_type):
super().__init__() # 调用父类的初始化方法 来完成基本的初始化
self.element_type = element_type
def append(self, object):
"""
:param object: 是要存储的元素
:return: 没有
"""
if type(object) == self.element_type:
#我们需要在这里访问父类的append函数来完成真正的存储操作
super(MyList,self).append(object)
else:
print("sorry sir, you element type not is %s" % self.element_type)
# 创建是指定要存储的元素类型
m = MyList(int)
# 当你有需求,是需要在创建对象时 干点什么事儿 那就该想到初始化方法
m.append(1)
print(m[0])
m.append("121212")
#4.字类访问父类
class Parent:
text = "abc"
def say_something(self):
print("anything")
class Sub(Parent):
def show_info(self):
# print(super(Sub,self).text)
# super(Sub,self).say_something()
# 访问方式2 py3的新语法 最常用的方式
print(super().text)
super().say_something()
#方式3 直接指定类名调用
# print(Parent.text)
# Parent.say_something(self)
# sub = Sub()
# sub.show_info()
# 5.初始化方法中的父类采用super()
class Person:
def __init__(self,name,gender,age,*args):
self.name = name
self.gender = gender
self.age = age
self.aa()
def aa(self):
print("aa run")
def say_hi(self):
print("name:%s ,gender:%s,age:%s" % (self.name,self.gender,self.age))
class Student(Person):
def __init__(self,name,gender,age,number):
super().__init__(name,gender,age)
self.number= number
def say_hi(self):
super().say_hi()
print("numnber:%s" % self.number)
stu = Student("rose","mael",20,"old01")
stu.say_hi()
# 6.组合
class Phone:
def __init__(self,price,kind,color):
self.price = price
self.kind = kind
self.color = color
def call(self):
print("正在呼叫XXXX;")
def send_message(self):
print("正在发送短信....")
class Student:
def __init__(self,name,gender,phone):
self.name = name
self.gender = gender
self.phone = phone
def show_info(self):
print("name:%s gender:%s" % (self.name,self.gender))
phone = Phone(1000,"apple","red")
stu1 = Student("rose","male",phone)
stu1.phone.call()
# 9.菱形继承(了解)
# py3 中是广域查找
# py2 中是深度查找
# py3中所有的类都是继承了源码中object的类,新式类
# py2中所有的类都不是继承源码中object的的类,旧式类