On the Python polymorphism and encapsulation

combination

What is a combination

A property of the object is an object of another class

Why use a combination of

You can reduce code redundancy

class Person:
    school = 'oldboy'
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))
  • Can be understood as a combination of more than one person to build a robot, and some artificial head, feet and some artificial, some artificial hand, some artificial torso, everyone was completed, the artificial torso head, foot, hand stitching to his torso on, so they built a robot out

Polymorphism and polymorphism

Polymorphism

What is polymorphism?

A variety of forms of a class of things

For example: animal: pigs, dogs, people

Polymorphism

Polymorphism refers to the use examples without considering Examples of types of

benefit

1. increase the flexibility of the program

2. Increase the amount of scalability program

Polymorphism

What is polymorphism

It refers to the Example without considering Examples of types of

Constraints Code

The first way: with a unified interface to implement abc, the code constraint (with less)

import abc
#第一在括号中写metaclass=abc.ABCMeta
class Animal(metaclass=abc.ABCMeta):
    #第二在要约束的方法上,写abc.abstractmethod装饰器
    @abc.abstractmethod
    def speak(self):
        pass

The second way, exception handling is achieved with the (common)

class Animal():
    def speak(self):
        #主动抛出异常
        raise Exception('你得给我重写它啊')

Advocating duck type: long walks like a duck (object has a binding method), then you are a duck

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

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, internal only be able to access
the hidden attribute: __ by the variable name to hide
concealment methods: the method name to hide by __

python actually can access the hidden properties
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._Person__name)

print(p.__dict__)
#通过变形隐藏了属性
Hiding

Isolation complexity

When the deformation properties

As long as another class internal to the variable name __ named variables will be hidden, deformed, and outside into the __ variable name attribute is not hidden

#计算人的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)
    
    
#property之setter和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)

Guess you like

Origin www.cnblogs.com/MrYang161/p/11425947.html