Advancing Python "sixth chapter": Python's Advanced Application (iii) object-oriented programming

Source: Internet
Author: User
Tags access properties class definition function definition


Advanced application of Python (iii) object-oriented programming


Key points to learn in this chapter:


    1. Introduction to Object-oriented programming
    2. The difference between object-oriented and process-oriented programming
    3. Why use object-oriented programming ideas
    4. Object-Oriented related concepts
introduction of Object-oriented programmingObject-Oriented Programming (English: object-oriented programming, abbreviation: OOP) is a programming paradigm and a method of program development.  An object refers to an instance of a class. It has been proved that object-oriented programming promotes the flexibility and maintainability of the program and is widely used in large-scale project design. In addition, supporters claim that object-oriented programming is easier to learn than ever before, because it allows people to design and maintain programs more easily, making them easier to analyze, design, and understand.  Opponents deny this in some areas. When we refer to object-oriented, it not only refers to a programming method. It is more of a program development approach. In this regard, we have to learn more about object-oriented system analysis and object-oriented design (object oriented, short Ood).two, object-oriented and process-oriented programming differencesThe process is to analyze the steps required to solve the problem, and then use the function to implement the steps one by one, the use of a one-time call on the right, the object is to make up the problem of the transaction into various objects, the object is not to complete a step,  But to describe the behavior of something in the whole process of solving the problem. Can take examples of life to understand the process-oriented and object-oriented, such as Gobang, the process-oriented design is the first step to analyze the problem: 1, start the game, 2, Sunspot first go, 3, draw the screen, 4, Judge Win and lose, 5, turn to white son, 6, draw the screen, 7, Judgment win, 8 Outputs the final result.  Implement each of the above steps in a different way. If it is an object-oriented design idea to solve the problem. Object-oriented design is to solve the problem from another idea. The whole Gobang can be divided into 1, black and white both sides, the behavior of the two parties is exactly the same, 2, the Board system, responsible for drawing the screen, 3, the rule system, responsible for determining such as foul, winning and losing.  The first Class object (Player object) is responsible for accepting user input, and informs the second class object (Checkerboard object) The change of the chess piece layout, the Checkerboard object receives the change of the chess piece to be responsible to display this kind of change on the screen, simultaneously uses the third kind of object (rule system) to determine the chess game. It is obvious that object-oriented is a function to divide a problem, not a step. The same is the game, the behavior in the process-oriented design scattered in a number of steps, it is likely to appear different drawing version, because the designers often consider the actual situation of a variety of simplification. In object-oriented design, the drawing can only appear in the Checkerboard object, thus guaranteeing the unification of the drawing.third, why to use object-oriented programming thinking


Object oriented is to solve the maintainability of the system, extensibility, reusability, we further consider, why the object-oriented to solve the system maintainability, extensibility, reusability?



The historical reasons for object-oriented generation include the following two points:



1, the computer is to help people solve the problem, but the computer is a machine, he will only follow the code written by people, step by step implementation, and finally get the results, so no matter how complicated the program, the computer can always easily cope. Structured programming is the code that is written according to the computer's thinking, but when people see such complex logic, they cannot maintain and extend it.



2, the structural design is to function as the goal to design the structural application system, this practice led us to design the program, we have to the object of the real world to map to a functional module composed of the solution space, this conversion process, the departure from the people to observe and solve the basic idea of the problem.



Visible structure design in the design of the system, can not solve the problem of reuse, maintenance, extension, but also lead to logic is too complex, the code is difficult to understand. So people think, can let the computer directly simulate the reality of the environment, with the human problem-solving ideas, habits, steps to design the appropriate application? Such a program, when people read it, will be easier to understand, and do not need to put the real world and the program of the world back and forth between the conversion.



At the same time, it is found that the object of existence in the real world is the protagonist in the problem domain. The so-called object refers to the objective entity and the subjective abstract concept, which has attributes and behaviors, and the object is stable, the behavior is unstable, and the object has all kinds of relations, so the object-oriented programming, the system will be more stable than the behavior-oriented programming. In the face of frequent changes in demand, the change is often behavior, and the object generally does not need to change, so we encapsulate the behavior, so that the change only need to change the behavior, the main structure remains stable.



So the object-oriented is produced.



But how is the system maintainability, extensibility and reusability embodied in the object-oriented?



First look at the three main features of object-oriented:



Encapsulation: To find the change and encapsulate it, you can modify or extend the changed parts of the package without affecting the other parts, which is the basis of all design patterns, that is, package changes, so the role of encapsulation, it solves the scalability of the program.



Inheritance: Subclass inherits the parent class, can inherit the parent class's method and the property, realizes the polymorphism as well as the code reuse, therefore also solves the system reusability and the expansibility. But inheritance destroys encapsulation because he is open to subclasses, and modifying the parent class causes all subclasses to change, so inheritance is somewhat disruptive to the system's extensibility, so inheritance needs to be used with caution. Only a definite is-a relationship can be used, while inheriting in the process of program development, rather than using inheritance at the beginning of programming, many object-oriented developers abuse inheritance, resulting in later code can not solve the changes in demand. Therefore, it is an important experience in object-oriented development to prioritize the use of combinations rather than inheritance.



Polymorphism: Many different implementations of interfaces are polymorphic. Interface is the abstraction of behavior, just mentioned in the encapsulation, find the change part and encapsulate it, but after encapsulation, how to adapt to the next change? This is exactly what the interface does, and the main purpose of the interface is to provide generic processing services for unrelated classes, which we can imagine. For example, a bird can fly, but Superman can fly, by flying this interface, we can let birds and Superman, both realize this interface, which realizes the system maintainability, extensibility.



Therefore, object-oriented can realize the system maintainability, extensibility and reusability that people pursue. Object-oriented is a kind of programming idea, at first, "object-oriented" refers to the design method of encapsulation, inheritance, polymorphism and so on, but the object-oriented thought already involves all aspects of software development, such as subdivision for object-oriented analysis (OOA), Object-oriented design (OOD), Object-oriented Programming implementation (OOP)


four, object-oriented related concepts
    • class: used to describe a collection of objects that have the same properties and methods. It defines the properties and methods that are common to each object in the collection. An object is an instance of a class.
    • Class variables: class variables are common throughout the instantiated object. Class variables are defined in the class and outside the body of the function. Class variables are not typically used as instance variables.
    • data members: class variables or instance variables are used to manipulate the data related to the class and its instance objects.
    • method Overrides: if the method inherited from the parent class does not meet the requirements of the subclass, it can be overridden, which is called the override of the method, also known as the override of the method.
    • instance variable: A variable defined in a method that acts only on the class of the current instance.
    • inheritance: A derived class (derived class) that inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as a base class object. For example, there is a design where an object of type dog is derived from the animal class, which is the analog "is a (is-a)" Relationship (example, dog is a animal).
    • instantiation: Creates an instance of a class, the concrete object of the class.
    • method: a function defined in a class.
    • object: An instance of a data structure defined by a class. The object consists of two data members (class variables and instance variables) and methods.
1. Create a class


Use the class statement to create a new class, followed by the name of the class and ending with a colon, as in the following example:


The class ClassName:
'class help info' # class docstring
Class_suite # class body
    • The Help information for the class can be viewed through classname.__doc__.
    • Class_suite consists of class members, methods, and data properties.
Here is a simple example of a Python class:
#! The/usr/bin/python
# -* -coding: utf-8 -*-

The class the Employee:
'base class for all employees'
EmpCount = 0

Def __init__ (self, the name, salary) :
The self. The name = name
Self. Salary = salary
The Employee. EmpCount + = 1

Def displayCount (self) :
Print ("Total Employee %d" % employee.empcount)

Def displayEmployee (self) :
Print ("Name: ", self.name, ", Salary: ", self.salary)
    • The Empcount variable is a class variable whose value is shared among all instances of the class. You can use Employee.empcount access in internal classes or outside classes.
    • The first method, the __init__ () method, is a special method called the constructor or initialization method of a class that is called when an instance of the class is created.
2. Create an Instance object


To create an instance of a class, you can use the name of the class and accept the arguments through the __init__ method.


"Create the first object of the Employee class"
Emp1 = the Employee (" Zara ", 2000)
"Create a second object of the Employee class"
Emp2 = the Employee (" Manni ", 5000)
3. Access Properties


You can use the dot (.) To access the properties of the object. Access the class variable using the name of the following class:


emp1.displayEmployee()
emp2.displayEmployee()
print("Total Employee %d" % Employee.empCount)


Complete Example:


#! The/usr/bin/python
# -* -coding: utf-8 -*-

The class the Employee:
'base class for all employees'
EmpCount = 0

Def __init__ (self, the name, salary) :
The self. The name = name
Self. Salary = salary
The Employee. EmpCount + = 1

Def displayCount (self) :
Print ("Total Employee %d" % employee.empcount)

Def displayEmployee (self) :
Print ("Name: ", self.name, ", Salary: ", self.salary)

"Create the first object of the Employee class"
Emp1 = the Employee (" Zara ", 2000)
"Create a second object of the Employee class"
Emp2 = the Employee (" Manni ", 5000)
Emp1. DisplayEmployee ()
Emp2. DisplayEmployee ()
Print ("Total Employee %d" % employee.empcount)


Execute the above code to output the result as follows:


Name :  Zara ,Salary:  2000
Name :  Manni ,Salary:  5000
Total Employee 2


You can add, remove, and modify the properties of the class as follows:


Emp1.age = 7 # add an 'age' attribute
Emp1.age = 8 # modify the 'age' attribute
Del emp1. Age # removes the 'age' attribute


You can also access properties by using the following functions:


    • GetAttr (obj, name[, default]): Accesses the properties of the object.
    • Hasattr (obj,name): Checks if a property exists.
    • SetAttr (Obj,name,value): Sets a property. If the property does not exist, a new property is created.
    • Delattr (obj, name): Deletes the attribute.
Hasattr (emp1, 'age') # returns True if the 'age' attribute exists.
Getattr (emp1, 'age') # returns the value of the 'age' attribute
Setattr (emp1, 'age', 8) # add attribute 'age' with a value of 8
Delattr (empl, 'age') # delete attribute 'age'
4. Python built-in class properties




    • __DICT__: Properties of the Class (contains a dictionary, consisting of the data properties of the Class)
    • __DOC__: Document string for Class
    • __NAME__: Class name
    • __MODULE__: The module where the class definition resides (the full name of the class is ' __main__.classname ', if the class is in an import module mymod, then classname.__module__ equals Mymod)
    • __BASES__: All parent classes of a class make up elements that contain a tuple of all the parent classes


The python built-in class property invocation instance is as follows:


#! The/usr/bin/python
# -* -coding: utf-8 -*-

The class the Employee:
'base class for all employees'
EmpCount = 0

Def __init__ (self, the name, salary) :
The self. The name = name
Self. Salary = salary
The Employee. EmpCount + = 1

Def displayCount (self) :
Print ("Total Employee %d" % employee.empcount)

Def displayEmployee (self) :
Print ("Name: ", self.name, ", Salary: ", self.salary)

Print (" Employee. __doc__ : "and the Employee. __doc__)
Print (" Employee. __name__ : ", the Employee __name__)
Print (" Employee. __module__ : ", the Employee __module__)
Print (" Employee. __bases__ : ", the Employee __bases__)
Print (" Employee. __dict__ : ", the Employee __dict__)


Execute the above code to output the result as follows:


Employee. S doc__: base class for all employees
The Employee. __name__ : the Employee
The Employee. __module__ : __main__
The Employee. __bases__ : ()
<function displaycount="" at="" 0x10a939c80="">, 'empCount' : 0, 'displayEmployee' : <function displayemployee="" at="" 0x10a93caa0="">, 's doc__' :</function></function> '\xe6\x89\x80\xe6\x9c\ x910 \x9a\ x9a\ x9a\ x9a\ x9f\xba\xe7\ XBB', 's} 
5. destructor------Python object Destruction


Like the Java language, Python uses a simple technique of reference counting to track objects in memory.



Inside Python is a record of how many references each object in use has.



An internal tracking variable, called a reference counter.



When the object is created, a reference count is created, and when the object is no longer needed, that is, the reference count of the object becomes 0 o'clock, and it is garbage collected. However, recycling is not "immediate", and the interpreter uses the garbage object to reclaim the memory space at the appropriate time.


A = 40 # creates an object <40>
B = a # adds references, <40>'s count
C = [b] # adds references. <40> counts

Del a # reduces the count of references <40>
B = 100 # reduces the count of references <40>
C [0] = -1 # reduces the count of references <40>


The garbage collection mechanism not only targets objects with a reference count of 0, but can also handle circular references. Circular references refer to two of objects referencing each other, but no other variables refer to them. In this case, using only the reference count is not enough. The Python garbage collector is actually a reference counter and a cyclic garbage collector. As a supplement to the reference count, the garbage collector also pays attention to objects that are allocated a large amount (and those that are not destroyed by reference counting). In this case, the interpreter pauses to attempt to clean up all unreferenced loops.


Instance
#! The/usr/bin/python
# -* -coding: utf-8 -*-

The class Point:
Def s init__(self, x=0, y=0):
Self. X = x
Self. Y = y
Def __del__ (self) :
Class_name = self. The magic __class__. __name__
Print (class_name, "destroy ")

Pt1 = Point ()
Pt2 = pt1
The pt3 = pt1
Print (id(pt1), id(pt2), id(pt3)) # print the id of the object
Del pt1
Del pt2
Del pt3


The results of the above example operation are as follows:


3083401324 3083401324 3083401324Point Destruction


Note: typically you need to define a class in a separate file


6 . Inheritance of Classes


One of the main benefits of object-oriented programming is the reuse of code, and one way to implement this reuse is through inheritance mechanisms. Inheritance can be fully understood as a type and subtype relationship between classes.



What to note: Inherit the syntax class derived class name ( base class name )://... The base class name is written in parentheses, and the base class is specified in the tuple at the time the class is defined.



Some of the characteristics of inheritance in Python:


    • 1: The construction of the base class in inheritance (The __init__ () method) is not automatically called, it needs to be called specifically in the construction of its derived class.
    • 2: When calling a method of the base class, you need to prefix the class name of the base class with the Self argument variable. Unlike calling a normal function in a class, you do not need to take the self argument
    • 3:python always looks for a method of the corresponding type first, and if it cannot find the corresponding method in the derived class, it begins to look in the base class one by one. (Find the method that was called in this class before you can find it in the base class).


If more than one class is listed in an inheritance tuple, it is called "Multiple inheritance."



Grammar:



The declarations of derived classes, like their parent class, inherit the list of base classes followed by the class name, as follows:


#! _ * _coding: utf-8 _ _
# __author__ : "Alex Li"



The class SchoolMember (object) :
Members = 0 # the initial school population is 0
Def __init__ (self, name, age) :
The self. The name = name
The self. The age = age

Def tell (self) :
pass

Def enroll (self) :
Register ' ' ' ' ' '
SchoolMember. Members + = 1
Print (" \ [033 32; 1 mnew member [% s] is enrolled, now there are [% s] members. \ [0 033 m "% (self. The name, SchoolMember. Members))

Def __del__ (self) :
Destructor method
Print ("\033[31;1mmember [%s] is dead!\033[0m" %self.name)
The class the Teacher (SchoolMember) :
Def __init__ (self, name, age, course, salary) :
The self, super (the Teacher) __init__ (name, age)
The self. The course = of course
Self. Salary = salary
Self. Enroll ()


Def would (self) :
Lecture method
Print ("Teacher [%s] is teaching [%s] for class [%s]" %(self.name,self.course, 's12'))

Def tell (self) :
Self-introduction method
MSG = 'Hi, my name is [%s], works for [%s] as a [%s] teacher! ' ' '% (self. The name, "Oldboy", the self. The course)
Print (MSG)

The class Student (SchoolMember) :
Def __init__ (self, name, age, grade, sid) :
The self, super (Student) __init__ (name, age)
Self. Grade = grade
Self. Sid = sid
Self. Enroll ()


Def tell (self) :
Self-introduction method
MSG = ' ' 'Hi, my name is [% s], I' m studying [% s] in [% s]! ' ' '% (self. The name, the self. The grade, "Oldboy")
Print (MSG)

If __name__ = = "__main__" :
T1 = the Teacher (" Alex, "22" Python ", 20000).
T2 = the Teacher (" TengLan ", 29, "Linux", 3000).

S1 = Student("Qinghua", 24,"Python S12",1483)
S2 = Student("SanJiang", 26,"Python S12",1484)

T1. Would ()
T2. Would ()
T1. Tell ()
7. Class properties and MethodsPrivate properties of the class


__private_attrs: Two underscores begin with, declaring that the property is private and cannot be used outside of the class or accessed directly. self.__private_attrswhen used in methods inside a class.


Methods of the class


Inside the class, using the DEF keyword, you can define a method for a class that differs from a generic function definition, which must contain the parameter self, and is the first argument


Private methods of the class


__private_method: Two underscores, declares that the method is a private method and cannot be called outside of a class. Calling Self.__private_methods inside a class


Instance
#! The/usr/bin/python
# -* -coding: utf-8 -*-

The class JustCounter:
S secretcount = 0 # private variable
PublicCount = 0 # expose variables

Def count (self) :
Self. __secretCount + = 1
Self. PublicCount + = 1
Print (self. __secretCount)

Counter = JustCounter ()
Counter. The count ()
Counter. The count ()
Print (counter. PublicCount)
Print (counter.s secretcount) # error, instance cannot access private variable


Python includes the class name by changing its name:


1
2
2
Traceback (most recent call last):
File "test.py", line 17, in <module></module>
Print counter. With an error, the instance cannot access the private variable
AttributeError: JustCounter instance has no attribute 's' s' s' s' s' s' s' s


Python does not allow instantiated classes to access private data, but you can use object._classname__attrname to access properties and replace the following code with the last line of code:


.......... print Counter._justcounter__secretcount (.....)


Execute the above code and execute the result as follows:


1222
8. Polymorphic


Before you talk about polymorphism, first a section of code:


The class Person (object) :
Def __init__ (self, name, sex) :
The self. The name = name
Self. Sex = sex

Def print_title (self) :
If self. Sex = = "male" :
Print (" man ")
Elif self. Sex = = "female" :
Print (" woman ")

Class Child(Person): # Child inherits Person
Def print_title (self) :
If self. Sex = = "male" :
Print (" boy ")
Elif self. Sex = = "female" :
Print (" girl ")

May = Child (" May ", "female")
Peter = Person (" Peter ", "male")

Print (May) name, May. Sex, Peter. The name, Peter. Sex)
May. Print_title ()
Peter. Print_title () 


When both the subclass and the parent class have the same Print_title () method, the subclass's Print_title () overrides the Print_title () of the parent class, and the subclass's Print_title () is called when the code runs.



In this way, we gain another benefit of inheritance: polymorphism .



The advantage of polymorphism is that when we need to pass in more subclasses, such as new teenagers, grownups, etc., we only need to inherit the person type, and the Print_title () method can not rewrite (that is, use person). can also be overridden by a unique. This is the meaning of polymorphism. The caller simply calls, regardless of the details, and when we add a subclass of person, just make sure the new method is written correctly without having to control the original code. This is the famous "opening and shutting" principle:


    • Open for extension: Allows subclasses to override method functions
    • To modify the enclosing (Closed for modification): Do not override, directly inherit the parent class method function





Advancing Python "sixth chapter": Python's Advanced Application (iii) object-oriented programming


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.