combination
What is a combination? A combination that is an attribute of the object is an object of another class
class Foo:
def __init__(self, bar):
self.bar = bar
class Bar:
pass
# f=Foo()
bar=Bar()
# f=Foo(Bar())
f=Foo(bar)
This is one of the most simple combination, the combination of what can get it?
Most useful combination is to reduce redundancy code
We can not have first to define a combination of parent and two sub-categories:
class Person:
school = 'oldboy'
class Teacher(Person):
def __init__(self,name, age, level, course_name,course_price,course_period):
self.name = name
self.age = age
self.level = level
class Student(Person):
def __init__(self,name,age,course,course_name,course_price,course_period):
self.name = name
self.age = age
self.course = course
So if you use a combination of, what will happen?
class Person:
school = '浦之星学院'
class Teacher(Person):
def __init__(self,name, age, level, course):
self.name = name
self.age = age
self.level = level
#course是课程对象,表示老师教授的课程
self.course = course
class Student(Person):
def __init__(self,name,age,course):
self.name = name
self.age = age
# course是课程对象,表示学生选的课程
self.course = course
class Course:
def __init__(self, course_name,course_price,course_period):
self.name = course_name
self.price = course_price
self.period = course_period
This reduces a lot of code redundancy
So how do we use a combination of it? Here still cite examples of schools, curriculum, teachers, students
class Person:
school = '音乃木坂学院'
class Teacher(Person):
def __init__(self,name,age,level,course):
self.name=name
self.age=age
self.level=level
#course是课程对象,表示老师教授的课程
self.course=course
class Student(Person):
# course=[] #错误
def __init__(self,name,age):
self.name=name
self.age=age
# course是课程对象,表示学生选的课程
self.course_list = []
def choose_course(self,course):
# self.course=[] #错误
#把课程对象追加到学生选课的列表中
self.course_list.append(course)
def tell_all_course(self):
#循环学生选课列表,每次拿出一个课程对象
for course in self.course_list:
#课程对象.name 取到课程名字
print(course.name)
class Course:
def __init__(self,course_name,course_price,course_period):
self.name=course_name
self.price=course_price
self.period=course_period
course=Course('Python',20199,7)
stu1=Student('nick',19)
stu1.choose_course(course)
stu2=Student('王二丫',19)
stu2.choose_course(course)
stu2.choose_course(Course('linux',19999,5))
So how do we see the names of all the courses it through the object stu1?
method one
By ordinary function
def tell_all_course(student):
for course in student.course_list:
print(course.name)
# tell_all_course(stu1)
tell_all_course(stu2)
Method Two
By binding method object
stu1.tell_all_course()
Polymorphism and polymorphism
What is polymorphism? Polymorphism is a variety of forms of the foods. For example, animals are pigs, dogs, people
Polymorphism refers to the use of examples, without considering the actual type
Polymorphic benefits:
Increasing the flexibility of the program
Increase the scalability of the program
Polymorphic base
class Animal:
def speak(self):
pass
class Pig(Animal):
def speak(self):
print('哼哼哼')
class Dog(Animal):
def speak(self):
print('汪汪')
class People(Animal):
def speak(self):
print('say hello')
pig=Pig()
dog=Dog()
people=People()
# pig.speak()
# dog.speak()
# people.speak()
def animal_speak(obj):
obj.speak()
animal_speak(pig)
animal_speak(people)
The first way
Abc can be used to implement the interface unification, constraint code, but generally not used
import abc
#第一在括号中写metaclass=abc.ABCMeta
class Animal(metaclass=abc.ABCMeta):
#第二在要约束的方法上,写abc.abstractmethod装饰器
@abc.abstractmethod
def speak(self):
pass
class Pig(Animal):
def speak(self):
print('哼哼哼')
class Dog(Animal):
def yy(self):
print('汪汪')
class People(Animal):
def zz(self):
print('say hello')
pig=Pig()
pig.speak()
# people = People() # 会报错
# people.zz()
But this can not take advantage of polymorphism
The second way
With exception handling implement (common)
class Animal():
def speak(self):
#主动抛出异常
raise Exception('你得给我重写它啊')
class Pig(Animal):
def speak(self):
print('哼哼哼')
class People(Animal):
# def speak(self):
# print('say hello')
pig=Pig()
pe=People()
def animal_speak(obj):
obj.speak()
animal_speak(pig) # 哼哼哼
animal_speak(pe) # 主动抛出异常
Advocating duck typing
As long walks like a duck (object has a binding method), then you are a duck
class Pig:
def speak(self):
print('哼哼哼')
class People:
def speak(self):
print('say hello')
pig=Pig()
pe=People()
def animal_speak(obj):
obj.speak()
animal_speak(pig)
animal_speak(pe)
Linux
#传统写法
class File:
def read(self):
pass
def write(self):
pass
#内存类
class Memory(File):
def read(self):
print('Memory...read')
def write(self):
print('Memory...write')
class Network(File):
def read(self):
print('Network...read')
def write(self):
print('Network...write')
# 鸭子类型的写法
# 内存类
class Memory:
def read(self):
print('Memory...read')
def write(self):
print('Memory...write')
class Network:
def read(self):
print('Network...read')
def write(self):
print('Network...write')
def read(obj):
obj.read()
m = Memory()
n = Network()
read(m)
read(n)
Package
Package What does it mean?
From meaning to understand the package itself,
the package as if it brought a sack, kitten, puppy, little bastard, along with a sack, and then seal the hole in the sack
How to hide, after packing things inside, hidden, not external access
How to hide in code
after the hidden attribute / Hide method to hide, not external access, only able to access the internal
Hidden attributes: variable name to hide by __
Concealment methods: the method name to hide by __
Hidden property for safety
#name 隐藏起来
# 隐藏属性是为了安全
class Person:
def __init__(self, name, age):
self.__name=name
self.__age=age
def get_name(self):
# print(self.__name)
return '[----%s-----]'%self.__name
p=Person('nick',89)
print(p.age)
#访问name
print(p.name)
print(p.__name)
print(p.get_name())
#隐藏的属性访问不到?实际上有方法能访问到
#通过变形隐藏了属性
print(p._Person__name)
print(p.__dict__)
#隐藏方法:隔离复杂度
class Person:
def __init__(self,name,age):
self.__name=name
self.__age=age
def __speak(self):
print('6666')
p=Person('nick',89)
p.__speak()
print(Person.__dict__)
p._Person__speak()
#什么时候属性变形,只要再类内部,以__变量名 命名的变量,都会被隐藏,会发生的变形,在外部放入的 __变量名 属性是不隐藏的
class Person:
def __init__(self,name,age):
self.__name=name
self.__age=age
def set_xx(self,xx):
self.__xx=xx
p=Person('nick',18)
# ._p_xx="xxx"
p.set_xx('6688')
print(p.__dict__)
#计算人的bmi指数
#property装饰器:把方法包装成数据属性
class Person:
def __init__(self,name,height,weight):
self.name=name
self.height=height
self.weight=weight
@property
def bmi(self):
return self.weight/(self.height**2)
# return self.weight/(self.height*self.height)
p=Person('lqz',1.82,70)
# print(p.bmi())
print(p.bmi)
# p.name='ppp'
p.bmi=90
The property setter and deleter
class Person:
def __init__(self,name,height,weight):
self.__name=name
self.__height=height
self.__weight=weight
@property
def name(self):
return '[我的名字是:%s]'%self.__name
#用property装饰的方法名.setter
@name.setter
def name(self,new_name):
# if not isinstance(new_name,str):
if type(new_name) is not str:
raise Exception('改不了')
if new_name.startswith('sb'):
raise Exception('不能以sb开头')
self.__name=new_name
# 用property装饰的方法名.deleter
@name.deleter
def name(self):
# raise Exception('不能删')
print('删除成功')
# del self.__name
p=Person('lqz',1.82,70)
# print(p.name)
# p.name='pppp'
# p.name='xxx'
#改不了,直接抛一异常
# p.name=999
# p.name='sb_nick'
# print(p.name)
del p.name
print(p.name)