Object-Oriented inheritance

Source: Internet
Author: User
Tags access properties

tags (space delimited): inheritance

What is inheritance:
Inheritance refers to the relationship between classes and classes, what is a "what" relationship, one of the functions of inheritance is to solve the problem of buying and selling, inheritance is a way to create new classes, in Python, the new class can inherit more than one parent class, the parent class can be a base class or a superclass, the new class is called a derived class or subclass ;

  • Inheritance in Python is divided into: single Inheritance and multiple inheritance:


Derived

Derivation: Is in the inheritance, subclasses have their own characteristics, have their own things, even the same method, subclasses can also have their own characteristics;

The implementation principle of inheritance:


Principles of Succession:
Depth first, breadth first;

After the subclass inherits, the method overrides the


If there are methods in the subclass, and rewrite, in the instantiation of the time, or the subclass of the method, if the sub-class can not find the use, inheritance;

  • Inheritance refers to the relationship between classes and classes;

For example: Course selection system:
Elective system inside: There are teachers, students, these can be defined as classes;

class Teacher:    school ='luffycity'    def __init__(self,name,age,sex,level,salary):        self.name=name        self.age=age        self.sex=sex        self.level=level        self.salary=salary            def teach(self):        print('%s is teaching '%self.name)class Student:    school ='luffycity'    def __init__(self,name,age,sex,class_time):        self.name=name        self.age=age        self.sex=sex        self.class_time=class_time    def learn(self):        print(%s is learning '%self.name)

The above code will find that we have a lot of duplicate code, there will be a lot of duplicate code, so for the repetition between classes of code, we can use inheritance, put the same function, encapsulation, and then inherit, as above we can, define a people, then the teacher and students inherit on the good;

So: the following code;

class People:    school = 'luffycity'    def __init__(self,name,age,sex):        self.name=name        self.age=age        self.sex=sex        class Teacher(People):    def __init__(self,name,age,sex,level,salary):        super().__init__(name,age,sex)        self.level=level        self.salary=salary            def teach(self):        print('%s is teaching '%self.name)class Student:    school ='luffycity'    def __init__(self,name,age,sex,class_time):        super().__init__(name,age,sex)        self.class_time=class_time    def learn(self):        print(%s is learning '%self.name)    teacher1 = Teacher('www',18,'male',10,3000)student1=Student('zhangsan',28,'feamal','18:34:45')

As the code above if: The teacher has the curriculum, the course period, the course price attributes, how to do it, the code is as follows: We can add properties to __init__

class People:    school = 'luffycity'    def __init__(self,name,age,sex):        self.name=name        self.age=age        self.sex=sex        class Teacher(People):    def __init__(self,name,age,sex,level,salary,course_name,course_price,course_period):        super().__init__(name,age,sex)        self.level=level        self.salary=salary        self.course_name=course_name        self.course_price=course_price        self.course_period=course_period            def teach(self):        print('%s is teaching '%self.name)class Student:    school ='luffycity'    def __init__(self,name,age,sex,class_time):        super().__init__(name,age,sex)        self.class_time=class_time    def learn(self):        print(%s is learning '%self.name)    teacher1 = Teacher('www',18,'male',10,3000,'python',3000,'dkkd')teacher1 = Teacher('aaa',18,'male',10,3000,'python',3000,'dkkd')

As the above code will have a lot of information about the course, wrote a lot of duplicate code;

So we can define a class individually:

  class People:school = ' Luffycity ' def __init__ (self,name,age,sex): Self.name=name        Self.age=age Self.sex=sex class Teacher (People): Def __init__ (Self,name,age,sex,level,salary,):        Super (). __init__ (Name,age,sex) self.level=level self.salary=salary def teach (self): Print ('%s is teaching '%self.name) class Student:school = ' Luffycity ' def __init__ (Self,name,age,sex,class_tim e): Super (). __init__ (name,age,sex) self.class_time=class_time def learn (self): print (%s is Learnin G '%self.name) class Course:def __init__ (self,course_name,course_price,course_period) Self.course_name =        Course_name self.course_price=course_price self.course_period =course_period def tell_info (self): Print (' Course name <%s> course Price <%s> pass to you cycle <%s> '% (self.course_name,self.course_price,self.course)] Teacher1.course.tell_info ()  

That's the combination.

Teacher1 =teacher (' Alex ', ' Male ', 10,3000,)
teacher1.course= ' python '
teacher2.course= ' python '

"";

Polymorphic

Polymorphism refers to a class of things that have many forms, such as animals in many forms: man, dog, pig

import abcclass Animal(metaclass=abc.ABCMeta): #同一类事物:动物    @abc.abstractmethod    def talk(self):        passclass People(Animal): #动物的形态之一:人    def talk(self):        print('say hello')class Dog(Animal): #动物的形态之二:狗    def talk(self):        print('say wangwang')class Pig(Animal): #动物的形态之三:猪    def talk(self):        print('say aoao')

To study polymorphism is to study the different states of the same thing,

Polymorphism: Refers to the direct use of an object without regard to the type of the instance,
Peo1=people ()
Dog1=dog ()
Pig1=pig ()

Peo1.talk ()
Dog1.talk ()
Pig1.talk ()

The above polymorphism, refers to the dynamic polymorphism, polymorphism, do not consider the specific instance type, it can be used directly;

def func(animal):    animal.talk()func(peo1)func(pig1)func(dog1)

Two reasons to use polymorphism (the benefit of polymorphism)

In fact, we can see from the above polymorphism example, we have not added any new knowledge, that is, Python itself is to support polymorphism, what is the benefit of doing so?

1. Increased flexibility of the program

Status quo, regardless of the ever-changing object, the user is the same form to invoke, such as func (animal)

2. Increased scalability of the program

By inheriting the animal class, a new class is created, and the user does not have to change their own code or use Func (animal) to invoke the
 
Python advocates duck type, that is, ' if it looks like, sounds like and walks like a duck, then it's a duck '

Python programmers usually write programs based on this behavior. For example, if you want to write a custom version of an existing object, you can inherit the object

You can also create a new object that looks and behaves like, but has nothing to do with it, which is typically used to preserve the loose coupling of program components.

Example 1: Use the various ' file-like ' objects defined in the standard library, although they work like files, but they do not inherit the method of the built-in file object

#二者都像鸭子,二者看起来都像文件,因而就可以当文件一样去用class TxtFile:    def read(self):        pass    def write(self):        passclass DiskFile:    def read(self):        pass    def write(self):        pass

Example 2: Sequence types have multiple forms: strings, lists, tuples, but they directly have no direct inheritance relationship

#str,list,tuple都是序列类型s=str('hello')l=list([1,2,3])t=tuple((4,5,6))#我们可以在不考虑三者类型的前提下使用s,l,ts.__len__()l.__len__()t.__len__()len(s)len(l)len(t)
Packaging

From the meaning of the package itself to understand, the package is like a sack, the kitten, puppy, Xiao Wang eight, and Alex together into the sack, and then seal the sack. According to this logic, encapsulation = ' hiding ', this understanding is quite one-sided

How to implement hiding:
  • Hide a property (set to private) in Python, starting with a double underscore
class A:    __N=0 #类的数据属性就应该是共享的,但是语法上是可以把类的数据属性设置成私有的如__N,会变形为_A__N    def __init__(self):        self.__X=10 #变形为self._A__X    def __foo(self): #变形为_A__foo        print('from A')    def bar(self):        self.__foo()        print('from bar')        #只有在类内部才可以通过__foo的形式访问到.#A._A__N是可以访问到的,即这种操作并不是严格意义上的限制外部访问,仅仅只是一种语法意义上的变形

Note: The above __n is a hidden property, note that python inside, with __ Beginning is hidden, to __, the end is Python built-in properties and methods, you remember! , don't confuse it;

Characteristics of deformation:
1. External no direct access to Obj.__attrname
2. Within the class can obj.__attriname, the answer is yes
3. Subclasses cannot overwrite attributes that begin with the parent class __ (because he is not a name of two)

The meaning of encapsulation

1. Encapsulating Data Properties: clear distinction between inside and outside

class People:    def __init__(self,name,age):        self.__name =name        self.__age=agep=People('egon',18)P.__name

Data attributes are not accessible externally, internally yes, but external can be indirectly accessed, we can open an interface within the class, access through the interface,

class People:    def __init__(self,name,age):        self.__name =name        self.__age=age    def tell_info(self):        print('Name:<%s> Age:<%s>' %(self.__name , self.__age))        p=People('egon',18)p.tell_info()

As the above code, we put the hidden attribute in: Tell_info (), the external instantiation of the object, to be accessed, just through the instance object. Tell_info () This method, which will be accessed through the interface method, convenient and fast;

2. The same code above, the user can not directly modify the name,age, we need to open an interface for users to modify;

class People:    def __init__(self,name,age):        self.__name =name        self.__age=age    def tell_info(self):        print('Name:<%s> Age:<%s>' %(self.__name , self.__age))    def set_info(self,name,age):        if not isinstance(name,str):            print("名字是字符串")            return        if not isinstance(age,str):            print("年龄是字符串")            return        self.__name =name        self.__age=age                p=People('egon',18)p.tell_info()P.set_info('EGON',38)#这里我们用的开的接口来修改的P.set_info('egon','12')
  • This is the encapsulation of our data attributes, the explicit distinction between inside and outside, the control of external to shadow property operation behavior;
The purpose of the encapsulation method
  • In order to: isolation of complexity;

For example I have an example of a withdrawal:

class ATM:    def __card(self):        print('插卡')    def __auth(self):        print('用户认证')    def __input(self):        print('输入取款金额')    def __print——bill(self):        print('打印账单')    def __take_money(self):        print('取款')    def withdraw(self):        self.__card()        self.__auth()        self.__input()        self.__print_bill()        self.__take_money()    a=ATM()    a.withdraw()
>* 如上述的代码可以看出,我们外部的实例通过,withdraw可以访问完全;
Encapsulation and Extensibility:

We have said before: the advantages of object-oriented: Scalability is high, in fact, packaging is also a high level of scalability;

class Room:    def __init__(self,namek,owner,height,weight,length)        self.name = name        self.owner=owner        #如果只想让用户访问:房间的长度和宽度,这里我们就可以把宽度和长度变为隐藏;        self.__weight=weight        self.__length=lengthr=Room('房间','wo',10,10)

1. If the problem comes, do we just want to access the area of the room rather than the property of the room?

class Room:    def __init__(self,namek,owner,height,weight,length)        self.name = name        self.owner=owner        #如果只想让用户访问:房间的长度和宽度,这里我们就可以把宽度和长度变为隐藏;        self.__weight=weight        self.__length=length            def tell_area(self):        return self._weight*self.__length        r=Room('房间','wo',10,10)print(r.tell_area())

As mentioned above, we only need to care about is: R.tell_area () What is the logic inside how we do not have to tube, which provides us with convenience, the expansion of the class;

  • What if the volume of the room is calculated?
class Room:    def __init__(self,namek,owner,height,weight,length,height)        self.name = name        self.owner=owner        #如果只想让用户访问:房间的长度和宽度,这里我们就可以把宽度和长度变为隐藏;        self.__weight=weight        self.__length=length        self.__height=height                    def tell_area(self):        return self._weight*self.__length*self.__height        r=Room('房间','wo',10,10)print(r.tell_area())

Also for the user, they do not need to care about the internal processing logic, they only need to invoke the good;

Use of property:

For example: The following description:

To implement the BMI program:

class People:    def __init__(self,name,weiht,height):        self.name=name        self.weight=weigth        self.height=heightP=People('ll',1.81,75)bmi=p.weight/(p.height ** 2)#或者可以写成如下的:p.bmi =p.weight / (p.height **2)print(p.bmi)

Problem:
As the above method of BMI, although we have achieved, but we have to define BMI every time, is not very troublesome, and BMI is not fixed, with the height and weight of people change, rather than static, then the question, how can we achieve simplification?

  • Here we can put the BMI, defined as a method, and then placed in the class, so that later instances only need to call this method is good, not every time the instantiation to calculate;
class People:    def __init__(self,name,weiht,height):        self.name=name        self.weight=weigth        self.height=height    def bmi(self):        return self.weight/(p.height ** 2)                P=People('ll',1.81,75)print(p.bmi())#bmi后边的()意味着调用函数

As the code above, for the user, he sees BMI as an exponent, plus () they do not understand, or it is misunderstood, for users they put the exponential BMI as a noun, rather than () method; What the user ultimately wants to achieve is P.BMI.
So to implement P.BMI I'm going to add a BMI () above the class, the adorner:

class People:    def __init__(self,name,weiht,height):        self.name=name        self.weight=weigth        self.height=height    @property    def bmi(self):        return self.weight/(p.height ** 2)P=People('ll',1.81,75)print(p.bmi())#bmi后边的()意味着调用函数

Add a point of knowledge: use of property:
For example, you define a property usage;

class People:    def __init__(sefl,name):        

What if we can't get a name like above?

Answer: We must get the name through the interface.

class People:    def __init__(sefl,name):        self.__name=name    def get_name(self):        return self.__name        p =People('egon') print(p.get_name())

Then for the user: they want to access properties, not through the method, otherwise users will be ignorant;

So the question is, how are we going to do it? (The answer is only to add adorners, such as code)

class People:    def __init__(sefl,name):        self.__name=name    @property    def get_name(self):        return self.__name        p =People('egon') print(p.name)

Here we use the property to illustrate, another property usage:

class People:    def __init__(sefl,name):        self.__name=name            @property    def name(sefl):        return self.__name    @name.setter    def name(self,val):        if not isinstance(val,str):            print('名字必须是字符串类型的')            return        self.__name =val    @name.deleter    def name(self):        print('不让删除')            p =People('egon') p.name #这里触发的是第一个,return self.__namep.name='DDD'#这个是访问行为,触发的是def name(self,val),如上述的修改的逻辑del p.name#删除属性

As mentioned above: we have to grasp, do not need to grasp too much;

@property    def name(sefl):        return self.__name
  • Summary, if some things can not be like attributes, need to set a method to implement, but the user wants to use these as attributes to access, rather than methods, () and so on, so we need the property decoration and other things to meet the needs;
    Here the above
@property    def name(sefl):        return self.__name
  • Is some things can not be directly accessed through the property, so the definition of a method, and then, we users do not understand what method is not method, the user to follow the property of a visit, so this time to use the adorner;

Object-Oriented inheritance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.