inherit
What is inherited
Inheritance is a relationship between two objects is described, what is the relationship between what
For example McDull, Paige, are Zhu A pig just mane,
In the program, describes the inheritance relationships between classes and class
E.g. inherited a b, a b can be used directly in existing methods and properties
called a subclass, b is called the parent class, also called a base class
class Base:
desc = "这是一个基类"
def show_info(self):
print(self.desc)
def make_money(self):
print("一天赚一个亿...")
#指定父类位Base
class SubClass(Base):
pass
obj = SubClass()
#即使类中什么都没有也可以使用父类中已有的内容
obj.make_money()
print(obj.desc)
Why use inheritance:
Inherited party may direct one party has inherited some things
Its purpose is to reuse existing code has been improved reusability
How to use inheritance
grammar:
class 类名称(父类的名称):
类的内容
#在python中 一个子类可以同时继承多个父类
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():
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
print("老师教学生,写代码....")
def say_hi(self):
print("name:%s,gender:%s,age:%s" % (self.name,self.gender,self.age))
t1 = Teacher("jack","male",20)
t1.say_hi()
SUMMARY exactly two classes, it is possible to reuse code through inheritance
class Teacher:
def __init__(self,name,gender,age):
self.name = name
self.gender = gender
self.age = age
def say_hi(self):
print("hi my name is %s age is %s gender is %s" % (self.name,self.age,self.gender))
class Student(Teacher): #指定Teacher类继承Student类
pass
#创建两个对象
t1 = Teacher("Jack","man",20)
t1.say_hi()
s1 = Student("Maria","woman",20)
s1.say_hi()
abstract:
Not specific, unclear, vague, not read
The same portion of the plurality of process subclasses, extraction, to form a new class, a process also known as abstract
The proper use of inheritance:
1.先抽象在继承
2.继承一个已经现存的类,扩展或是修改原始的功能
# 抽取老师和学生中相同的部分形成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):
def teaching(self):
print("老师教学生,写代码....")
t1 = Teacher("jack","male",20)
t1.say_hi()
class Student(Person):
pass
stu1 = Student("rose","female",18)
stu1.say_hi()
list
Property search order
class A:
text = "haha"
class B(A):
text = "heihei"
pass
b = B()
b.text = "xixi"
print(b.text)
The object itself -> where the class -> find parent -> parent class parent -> Object
Derivation
When a subclass occurred with different content parent class, subclass it is called a derived class
Usually sub-class will write some new code, and the parent can not be exactly the same, both are usually derived class,
So derived class refers to a subclass
cover
Also known as rewrite overrides
When the sub-category appear entirely consistent with the name of the parent class property or method
class Person:
def say_hi(self):
print("hello")
class Student(Person):
def say_hi(self):
print("hello world!")
stu = Student()
stu.say_hi()
Exercise:
A restriction element can be implemented types of containers (dictionary, list, tuple, set, String)
1.list: ready-made "classes"
class MyList(list):
pass
m=MyList()
m.append(2)
print(m[0])
#2
2. Code
class MyList(list):
def __init__(self,element_type):#当有需求在创建对象时,干点什么事,就想到初始化方法。
self.element_type=element_type
def append(self,object):
if type(object)==self.element_type:#此处限制类型
super().append(object)#在子类中访问父类list的元素
else:
print('sorry sir your element isnt %s'%self.element_type)
m=MyList(int)#此处指定类型
m.append(2)
print(m[0])
m.append('1')
print(m[0])
Subclass the parent class content access
grammar:
方式1:
super(当前类名称,self).你要调的父类的属性或方法
方式2:
super().你要调的父类的属性或方法
方式3:
类名称.你要调的父类的属性或方法(self)
#方式3与继承无关
He stressed stressed:
When you inherit an existing class, and you override the parent class init method, you must call the parent class initialization method of the first line of the initialization method, passing in the required parameters parent class
# class Person:
# def __init__(self,name,gender,age):
# self.name = name
# self.gender = gender
# self.age = age#
# 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()
# 为什么要在初始化方法中调用 父类的初始化方法
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()
combination
It is also a relationship, describing what is what is the relationship between two objects
For example, students have cell phones, game characters have certain equipment
An object as a property of another object, (both what what)
The purpose of the combination:
Also to reuse existing code
When to use inheritance: analysis of the relationship between two classes, in the end is not: What is the relationship between what
When to use a combination of: if there is no significant relationship between the two classes, do not belong to the same
Further, compared hierarchical composition, the lower the degree of coupling
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()
Knowledge of point
Diamond inheritance
First clear python support multiple inheritance
# 菱形继承
# class A:
# j = 1
# pass
#
# class B:
# # j = 2
# pass
#
# class C(A):
# # j = 3
# pass
#
# class D(A):
# j = 4
# pass
#
# class E(B,C,D):
# # j = 5
# pass
#
# d = E()
# print(d.j)
class B:
# num = 2
pass
class C:
# num = 3
pass
class E(B):
# num = 5
pass
class F(C):
# num = 6
pass
class G(C):
num = 7
pass
class H(E,F,G):
# num = 8
pass
print(H.num)
# print(H.mro())
#[H,E,B,F,G,C,object]
Added: new-style class and Classic
Python3 in any class are inherited directly or indirectly Object
New class, any explicit or implicit object inherits from class to the new class is called, all of the new class to python3
Classic, is neither a subclass of Object, occurs only in python2
When there is a diamond inheritance, the new class, the first depth, when faced with a common parent class on breadth
新式类,就是深度优先
summary:
1. What is the inheritance
2. Why inheritance
3. Grammar
4. In the first abstract inheritance
6. derived
7. cover
8. The method of super or sub-class attribute of access to the parent class () Name
如果你继承一个已有的类,并且你覆盖了init 一定要先调用父类的init
9. inheritance principle, mro list
10, new classes and Classic
11. diamond inheritance understand
12, attribute search order