Python Basics (16) _ Object-oriented programming (class, inheritance, derivation, composition, interface)

Source: Internet
Author: User

process-oriented programming and object-oriented programming

process-Oriented programming : The core is the process, process on the steps to solve the problem, based on the idea of the design process is like a pipeline, is a mechanical way of thinking
Advantages: Simplification of complex problems, flow of
Cons: Poor scalability

Object-Oriented programming : The core is the object, the object is a combination of characteristics (variables) and skills (functions), is a kind of God-like way of thinking

Advantages: It solves the extensibility of the program

Cons: Poor controllability

ii. Classes and Objects

A game for example, based on the object-oriented design of a game: League of Legends, each player to choose a hero, each hero has its own characteristics and skills, characteristics of data attributes, skills is the method attributes, characteristics and skills of the combination of an object .

class : extracting a similar part from a set of objects is a combination of features and skills that all objects of a class have

In Python, a variable represents a feature, a function represents a skill, and a class is a combination of a variable and a function, and an object is a combination of a variable and a method (a function that points to a class).

In the real World: objects-(common features and skills)--Class
In the program: Define class----(instantiate)-----> objects

1. Definition of class

To define the syntax of a class
Class Name:
"' Notes '
Class Body

#定义一个学生类: The class name is usually capitalized to indicate class Student:    school = ' Oldboy '    def __init__ (self,name,age):        #只用来初始化的, and must not have a return value ,        self.name=name        self.age=age    def study (self):        print (' is studying ')    def Fly (self,x):        print (x)        print ('%s is flying '%self.name)    def foo (self):        print (' =========== ")

2, the role of the class

Usage of the class one: instantiating the resulting object
Use of the Class two: Property reference

3, the role of the object:

Object/instance has only one function: Property Reference

#类的作用一: Instantiate an object S1=student (' Egon1 ', ") s2=student (' Egon2 ',") #类的作用二: The class's properties refer to print (Student.school) #引用类的数据属性print ( Student.study) #引用类的函数属性 # Object Usage: Property Reference print (S1.name) print (s1.age)

The object/instance itself has only data properties, but the Python class mechanism binds the function of the class to the object, called the object's method, or is called a binding method, the binding method uniquely binds an object, the method of the same class binds to a different object, and it belongs to a different method. Memory addresses are not the same

4. Class namespace and Object namespace

Creating a class creates a namespace for a class that stores all the names defined in the class, called Properties of the class

A class has two properties: Data properties and Function properties,

  Where the data properties of a class are shared to all objects

>>> ID (s1.school) #本质就是在引用类的Student属性, both IDs 4315241024>>> ID (s2.school) 4315241024

  The function properties of a class are bound to all objects:

>>> ID (s1.study) 4302501512>>> ID (s2.study) 4315244200

Creating an object/instance creates an object/instance namespace that holds the name of the object/instance, called the object/instance property

In the Obj.name will first find the name in Obj's own namespace, can not find the class to find, the class can not find the parent class ... Throw an exception if you can't find it at the end

Supplement to class attributes

A: Where do the properties of the class we define are stored? There are two ways to view Dir (class name): A Name list class name is detected. __dict__: A dictionary is found, key is the property name, value is the attribute two: Special Class attribute class name. __name__# class Name (String) class name. __doc__# Class name of the document String class. The first parent class of the __base__# class (Speaking of inheritance) class name. A tuple of all the parent classes of the __bases__# class (Speaking of inheritance) class name. The class name of the dictionary attribute of the __dict__# class. The __module__# class defines the module class name. Class for __class__# instances (in modern class only)

  

Iii. inheritance and derivation

1, the concept of inheritance: inheritance is a way to create a new class, in Python, the new class can inherit one or more parent classes, the parent class can also be called a base class or a superclass, a new class is called a derived class or subclass

The inheritance of classes in Python is divided into: single inheritance and multiple inheritance

Class ParentClass1: #定义父类    passclass ParentClass2: #定义父类    passclass SubClass1 (PARENTCLASS1): #单继承, The base class is ParentClass1, and the derived class is the subclass    #python支持多继承, separating multiple inherited classes with a comma    pass

View Inheritance

>>> subclass1.__bases__ #__base__只查看从左到右继承的第一个子类, __bases__ is to view all inherited parent classes (<class ' __main__. ParentClass1 ',,) >>> subclass2.__bases__ (<class ' __main__. ParentClass1 ';, <class ' __main__. ParentClass2 ' >)

Note: In Python3 All classes inherit object by default,

1, as long as it inherits the subclass of the object class, and the subclass of the subclass, is called the New class (the class in Python3 is a new class)

2. Subclasses that do not inherit the object class are called Classic classes (in Python2, classes with no integrated object, and its subclasses, are classic classes)

' Inherit + Derive ' class people:    def __init__ (self, Name, age,sex):        self.name = name        Self.age = Age        self.sex= Sex    def walk (self):        print ('%s was walking '% self.name)    def foo (self):        print (' From Father%s '%self.name ) class Teacher (people):    school = ' Even fraternity '    #__init__ (t, ' Egon ', ' Male ', 10,3000)    def __init__ (self, name, age,sex,level,salary):        people.__init__ (self,name,age,sex)        self.level=level        self.salary=salary    def teach (self):        print ('%s was teaching '%self.name)    def foo (self):        People.foo (self)        print (' from teacher ') class Student (People):    def __init__ (self, Name, Age,sex,group):        people.__init__ (Self, name , age, Sex)        Self.group=group    def study (self):        print ('%s is studying '%self.name) t=teacher (' Egon ', 18, ' Male ', 10,3000)
Iv. Combination and reusability

A combination refers to a class in which an object of another class is used as a data property, called a combination of classes

Combination and inheritance are important ways to make effective use of existing classes of resources. But both concepts and usage scenarios are different,

1. Ways of inheriting

The relationship between the derived class and the base class is established through inheritance, which is a ' yes ' relationship, such as a horse in a white horse and a human being an animal.

When there are many identical functions between classes, extracting these common functions into a base class is better with inheritance, for example, a professor is a teacher.

>>> class Teacher: ...     def __init__ (self,name,gender): ...         self.name=name ...     Self.gender=gender ... def teach (self): ...         Print (' teaching ') ... >>> >>> class professor (Teacher): ...     Pass ... >>> p1=professor (' Egon ', ' Male ') >>> P1.teach () teaching

2. Combination of ways

The relationship between classes and classes is established in a combinatorial way, which is a ' have ' relationship, such as a professor having a birthday, teaching a python course

Class BirthDate:    def __init__ (self,year,month,day):        self.year=year        self.month=month        self.day= Dayclass couse:    def __init__ (self,name,price,period):        self.name=name        self.price=price        Self.period=periodclass Teacher:    def __init__ (self,name,gender):        self.name=name        Self.gender=gender    def teach (self):        print (' teaching ') class professor (Teacher):    def __init__ (Self,name,gender,birth, Course):        teacher.__init__ (self,name,gender)        Self.birth=birth        self.course=coursep1=professor (' Egon ', ' Male ',             BirthDate (' 1995 ', ' 1 ', ' the ') ',             couse (' python ', ' 28000 ', ' 4 months ')) print (P1.birth.year, P1.birth.month,p1.birth.day) Print (p1.course.name,p1.course.price,p1.course.period) "Run Result: 1 27python 28000 4 Months ""

Inheritance + derivation + combination application Examples:

class people:def __init__ (self, name, age, year, Mon, day): Self.name = Name Self.age = Age Self.birth = Date (year, Mon, day) def Walk (self): print ('%s was walking '% self  . Name) class Date:def __init__ (self,year,mon,day): Self.year=year Self.mon=mon self.day=day def Tell_birth (self): print (' Born <%s> year <%s> month <%s> Day '% (self.year,self.mon,self.day)) class Teacher (peopl        E): Def __init__ (self, name, age, year, Mon, day,level,salary): people.__init__ (Self,name,age,year,mon,day) Self.level=level self.salary=salary def teach (self): print ('%s is teaching '%self.name) class Student (P        eople): Def __init__ (self, name, age, year, Mon, Day,group): people.__init__ (Self,name,age,year,mon,day) Self.group=group def study (self): print ('%s is studying '%self.name) 

Summary: when classes are significantly different, and the smaller classes are the components needed for larger classes, the combination is better 

Five, interface

There are two uses of inheritance:

One: Inherit the methods of the base class and make your own changes or extensions (code reuse)

Two: Declare a subclass is compatible with a base class, define an interface class interface, the interface class defines some interface names (that is, the function name) and does not implement the functions of the interface, subclasses inherit the interface class, and implement the functions in the interface

Class Interface: #定义接口Interface类来模仿接口的概念, there is no Interface keyword in python to define an interface.    def read (self): #定接口函数read        pass    def write: #定义接口函数write        passclass Txt (Interface): #文本, Specific implementation of Read and write    def read (self):        print (' Read method of text data ')    def write:        print (' Read method of text data ') class Sata ( Interface): #磁盘, implementation of Read and write    def read (self):        print (' Read method of hard drive data ')    def write ('):        print (' Hard drive data Read method ') class Process (Interface):    def read (self):        print (' Read method of process data ')    def write (self):        Print (' Read method of process data ')

In practice, the first meaning of inheritance is not very significant, and often harmful. Because it causes the subclass to be strongly coupled to the base class.

The second meaning of inheritance is very important. It is also called "Interface inheritance."
Interface inheritance is essentially a requirement "to make a good abstraction, which prescribes a compatible interface so that the external caller does not have to care about the specifics, and treats all the objects of a particular interface in a non-discriminatory process"--this is called Normalization in program design .

Normalization allows high-level external users to handle the collection of objects that are compatible with all interfaces without distinction-just like the generic file concept of Linux, everything can be treated as a file, regardless of whether it is memory, disk, network, or screen (of course, for the underlying designer, it can also distinguish between "character devices" and " And then make a specific design: to what extent, depending on the requirements.

Benefits of the interface:

The interface extracts a group of common functions that can be used as a collection of functions. Then let the subclass implement the functions in the interface.

The significance of this is normalization, what is called normalization, that is, as long as it is based on the same interface implementation of the class, then all of these classes produce objects in use, from the usage of the same.

Normalization, so that users do not have to care about the object's class, only need to know that these objects have certain functions, which greatly reduces the user's use of difficulty.

"(abstract Class): #父类要限制 # #; A subclass must have a method of the parent class #: The subclass implements a method that must be the same as the name of the parent class's method " Import Abcclass File (METACLASS=ABC. Abcmeta):    @abc. Abstractmethod    def read (self):        pass    @abc. Abstractmethod    def write (self):        Passclass Txt (File): #文本, specifically implemented read and write    def read (self):        pass    def write:        passt=txt ()

  

Python Basics (16) _ Object-oriented programming (class, inheritance, derivation, composition, interface)

Related Article

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.