Python Basics-day sixth-object-oriented programming

Source: Internet
Author: User
Tags webp

The content of this article

1. Introduction to Object-oriented programming

2. Definition of class and introduction of various parts

3. Properties

4. Methods

5. Object-oriented features-encapsulation

6. Object-oriented features-inheritance

7. Object-oriented features-polymorphism

8. New class and Classic class



Introduction of object-oriented programming

1. Principles of Programming

Regardless of the programming paradigm to remember the principle is to avoid writing duplicate code, the code is easy to expand. Be sure to follow the principle of good readability and easy extension.


2. Object-oriented programming (Object-oriented programming) Introduction

The main function of OOP programming is to make code modification and extension easier;

Object-oriented programming is the use of classes and objects to help us implement functionality. Class is a function, each function can be a function, the difference is that we cannot directly call the function outside the class, we must use the object to invoke the function, and the object is generated by instantiating the class.

In Python everything is an object, and the string, list, and so on in Python are all objects.

Each object has properties, such as the object's name, color, and so on.

Each object has a function (that is, a method), such as Append (), which is one of the functions of the list.

In Python, pass the "." To invoke the function of the object.


3. Object-oriented concepts and features

① concept

Class (classes)

A class is an abstraction, a blueprint, a prototype for a class of objects that have the same properties. The attributes (variables (data)) and common methods (which can also be understood as functions) of these objects are defined in the class.

Object (Objects)

An object is an instantiated instance of a class, a class must be instantiated before it can be called in the program, a class can instantiate multiple objects, each object can also have different properties, like human refers to all people, each person refers to the specific object, there are similarities between people, there are also different.

The object that is generated by the class is called instantiation, and the object can also be called an instance;


② characteristics

Encapsulation (Package)
The assignment of data in a class, internal invocation is transparent to external users, invisible, which makes the class become a capsule or container, in which the bread implies the data and methods of the class;

Effect: 1. To prevent the data from being arbitrarily modified; 2. The external program does not need to pay attention to the structure or logic inside the object, only through the interface provided by the object to access it; 3. Avoid writing duplicate code;

Inheritance (inheritance)
A class can derive a subclass, and the properties, methods defined in the parent class automatically inherit the quilt class.

By inheriting the parent class in a subclass, you can implement different objects with a minimum amount of code in common and with different points.

The main function of inheritance is to avoid writing duplicate code;

Polymorphism (polymorphic)
Polymorphism is an important feature of object-oriented, simple point: "An interface, a variety of implementations", refers to a base class derived from a different subclass, and each subclass inherits the same method name, but also the parent class method to do a different implementation, this is the same thing shows a variety of forms.
Programming is actually a process of abstracting the concrete world, which is a manifestation of abstraction, abstracting the common denominator of a series of specific things, and then through this abstract thing, and dialogue with different concrete things.
Sending the same message to different classes of objects will have different behavior. For example, if your boss lets all employees start working at nine o'clock, he says "get started" at nine o'clock, instead of saying to the salesperson: "Start a sales job," say to the technician, "Start technical work", because "employee" is an abstract thing, so long as the employee can start to work, He knows that. As for each employee, of course, they do their job and do their jobs.
Polymorphism allows the object of a subclass to be used as an object of the parent class, a reference to a parent type to an object of its subtype, and the method called is the method of that subtype. The code that references and calls the method here is determined before it is compiled, and the object that the reference points to can be dynamically bound during the run.



Ii. definition of class and introduction of various parts

1. Definition of class

Class person (object):  #  The first letter of all the words in the class name, using the method of writing the Hump (example CamelCase);     #   properties that are directly defined in a class are public properties     nationality =  "CN"     def __ init__ (Self, name, age):  #  constructor         self. name = name  #  Common Properties, equivalent to P1. name =  "Jack"         self.age = age         #  private properties are invisible outside, and are visible inside          self.__money =  method functions for the "1W"     def talk (self):  #  class          print ("%s  is speaking Chinese"  % self. Name) the     def get_money (self):  #  class method function, which functions as a read-only access interface to externally provided private properties          #  private properties can only be called inside a class and cannot be called outside of a class       &Nbsp; self.__money =  "2W"         print (Self.__money)         return self.__money             def __del__ (self):  #  destructor          print ("Example:  %s dies"  % self. Name)

① constructor function

__init__ This function is a constructor, the constructor defines a common attribute

The arguments passed at instantiation are passed to the constructor. If you do not need to pass parameters to the constructor, you do not have to define constructors;


Method functions for the ② class

Define common functionality for all objects

A method function of a class is a public method that only holds a copy of the


③ Public properties (also known as static properties)

A property that is directly defined in a class is a public property, and the public attribute and constructor, and the method function of the class are peer. Here is a detailed description


④ Private Properties

A private property can only be called internally and cannot be called externally.


⑤ Destruction function

Destructors are automatically executed when the instance is destroyed. The above __del__ is a destructor;

Deleting an object with Del and destroying the instance at the end of the program will also execute the destructor;

Destructors can be used to do the finishing work of the program, such as closing open files, etc.;


The role of ⑥self

In fact, self is the instance itself, and when instantiated, Python automatically passes the instance itself through the arguments. Self exists to solve the problem of having access to object properties in all functions in a class.


2. Instantiation

P1 = person ("Jack", 33) # Instantiates the class-generated object, equivalent to the person (P1, "Jack", "a") P2 = Person ("Eric", 33) # Instantiates the class-generated object, equivalent to person (P2, "Eric", 28)

Note that although both P1 and P2 are instantiated through the person class, p1 and P2 are two non-pass objects. For example, human represents all people, but people are specific to each different person, here the person class is human, P1 and P2 is a specific person.


3. Calling Object methods

P1.talk () # Caller's speech function, equivalent to D1.talk (p1)

When the method function of a class requires additional arguments, the arguments are written in parentheses when the method function is called;



Third, attribute

Attributes are: Member property, private property, and public property (static property);


1. Member properties

When instantiated, the property passed to the constructor initialization is called a member property, or it can be called a member variable or an instance property;

The above name and age are member attributes;


2. Private properties

A private property can only be called internally and cannot be called externally.

A private property is defined in a constructor;

The naming rules for private properties are two underscores plus variable names, and the above __money are private properties;

Because private properties can only be called internally, what happens when external calls are required? The Get_money method function above is an interface that provides external calls to private properties, returning a private property through return.


3. Public properties (static properties)

Properties that are accessible to all objects belonging to this class are public properties

A property that is directly defined in a class is a public property, and the public attribute and constructor, and the method function of the class are peer. The above nationality is a public attribute;

Why you need public properties, imagine, now there is a need to generate all the Chinese through the Chinese class, the generation of each Chinese is a separate object, they have a common nationality attribute is China, and the instance attribute is encapsulated in each object, then the question comes, the nationality attribute needs to save 1.3 billion copies, With the public attribute, only one copy of the class is saved.


① methods for accessing public properties

Direct access through the class

Print (person.nationality) # go directly to the class to find, found the return, not found on the error.


Access by object

# first go to the object to find, find the direct return, if not found, then go to the class to find, found on the return, did not find the error. Print (p1.nationality)


② Modifying the value of a public property

Modify by Class

# modifies the public property through the class, modifying the value of the public property saved in the class. is a global modification that modifies all person.nationality = "JP"


Modify by Object

# By modifying a public property through an object, a member property is initialized directly in the object with the name of the public attribute and the value of the content to be modified. p1.nationality = "JP"



Iv. methods

The methods of the class are divided into: ordinary method (or dynamic property), static method


1. Common methods (or dynamic properties )

The common method is the public method, such as the above talk, Get_money function is the ordinary method, only in the class to save a copy;

The caller of the normal method is the object, which is to invoke the ordinary method through the object;

A normal method requires at least one self parameter;


2. Static methods

Why do I need a static method? If we create a class in which there are no constructors, only methods, in which case, if you want to invoke a method in a class, you must first instantiate the object and then invoke the method in the class through the object. So doing this causes the class and object to occupy the memory space, and the function to do the implementation of the same effect, and the function occupies less memory space, then we need to use a static method to solve the problem.

Static methods allow direct invocation without the creation of an object, which is not required to be called through an object, and can be called directly from a class;

When you add @staticmethod to a method function, the method function becomes a static method:

@staticmethoddef Talk: # static method Print ("%s is in Chinese"% self.) Name) Person.talk () # is called directly through the class



V. Object-oriented features-encapsulation

Encapsulation, as the name implies, encapsulates the content somewhere and then calls the content that is encapsulated somewhere.

Encapsulation in a class is: public properties, constructors, dynamic properties (or Common methods), static methods;

Encapsulated in an object with: The value of the member property (normal property);

When using the object-oriented encapsulation feature, you need to know that encapsulating the content somewhere will call the encapsulated content from somewhere.

When the encapsulated content is called, there are two cases: direct invocation through an object, indirect invocation via self (in the method function of the class, the encapsulated content needs to be indirectly called through self);



Vi. Object-oriented features-inheritance

1. What is inheritance

Inheritance in object-oriented is the same as inheritance in real life, where the child can inherit the contents of the parent.

Inheritance refers to the ability to use all the functionality of an existing class and to extend these capabilities without rewriting the original class. So the main function of inheritance is code reuse;

New classes created through inheritance are called subclasses or derived classes. The inherited class is called the base class, parent class, or superclass.


2. Implementing inheritance

To implement inheritance, it can be implemented in two ways, inheritance (inheritance) and combination (composition).

In some OOP languages, a subclass can inherit multiple base classes. However, in general, a subclass can have only one base class, and to implement inheriting multiple classes, it can be implemented by multiple inheritance (inheriting multiple classes at the same time) and multilevel inheritance (there are subclasses under the parent class, and the child classes below, and the grandchildren class).

There are two main ways to implement the concept of inheritance: implementation of inheritance, interface inheritance. Implementation inheritance refers to the ability to use the properties and methods of the base class without additional coding; Interface inheritance is the ability to use only the names of properties and methods, but the subclass must provide the implementation (subclass refactoring parent method);


3. Inherited syntax

Single inheritance

class Person (object): # parent class Def __init__ (self, Name, age): Self.name = name Self.age = Age def talk (SE LF): print ("People talking") class Blackperson (person): # Brackets Write the inherited class Def walk (self): print ("The Negro is Walking") # Blackpe The Rson class inherits the constructors and talk methods of the person class.

Therefore, for object-oriented inheritance, it is actually the method of extracting multiple classes common to the parent class, and the subclass inherits only the parent class without having to implement each method in one.


Multiple inheritance

Class schoolmenber (object):     "" "School member base class" "    member = Total number of  0  #  School members     def __init__ (self, name, age,  Sex):         "" "        :p Aram  name:  name         :p aram age:  Age          :p aram sex:  sex          "" "" "         self.name = name         self.age = age        self.sex = sex         self.enroll ()   #  automatic registration automatically calls the registration function as soon as one instantiation      def enroll (self):         "" "Register Function" ""        &nbSp; print ("Register a new School member:  %s"  % self.name)          schoolmenber.member += 1  #  each new member is registered, the public attribute member will be added a     def  Tell (self):         "" "  Print member information" ""          print ("----- info: %s -----"  % self.name)          for key, value in self.__dict__.items ():             print ("\t%s: %s"  %  (key, value))      def __del__ (self):         "" "destructor to automatically execute" "When the instance is destroyed         print ("Member:  %s was expelled"  % self.name)          schoolmenber.member -= 1class school (object):      "" "School Class" ""  &nbsP;  def open_branch (SELF, ADDR):         "" "          functions         :p aram  Address of the addr:  campus         :return:          "" ""         print ("New campus at:  %s"  % addr) Class teacher (schoolmenber, school):  #  Brackets Write inherited classes      "" "Instructor Class" "     def teaching (self):         "" "Teaching Function" ""         print ("%s instructor is speaking%s course"  %  (Self.name, self.course))

When the object called by the Teacher class instantiation method, first in the teacher class to find, did not find the Schoolmenber class to find, and finally go to the school class, if not found on the error.


4. Inheritance and refactoring

Sometimes we need to inherit the method from the parent class, and what about adding something else to the method?

Class person (object):  #  parent class     def __init__ (Self, name,  age):        self.name = name         self.age = age    def talk (self):         print ("People Talking") Class blackperson (person):  #  Brackets write inherited classes      #  first inherits, then reconstructs     # self The current instance is also passed in, so the self represents the current instance      #  instantiation when name, age is passed to the parent class, strength is passed to the subclass     def __init__ (self,  Name, age, strength):        #  inherit constructors in the person class          # self is passed in the current instance to the subclass at instantiation, and the subclass then passes the current instance to the parent class          # name and age are two arguments passed in to the subclass when instantiated, and the subclass passes the two arguments to the parent class          #  Classic and New classWriting the same effect, now mainly write new class         # person.__init__ (self, name,  Age)   #  Classic class notation         super (blackperson, self). __ init__ (name, age)   #  new class         self.strength  = strength  #  Subclass unique attribute     def talk (self):         #  to inherit the Talk method function in the person class         #  self is passed in the current instance to the subclass at instantiation, and the subclass then passes the current instance to the parent class         # person.talk (self)   #  Classic class notation         super (blackperson, self). Talk ()   #  new class         print ("Black Talking")      def walk (self):         print ("The Negro is Walking")



Vii. Object-oriented characteristics-polymorphism

Polymorphism is an important feature of object-oriented, simple point: An interface, a variety of implementations;

Interface reuse, but the form of expression is not the same;

Python does not directly support polymorphism, but can be implemented indirectly, advocating "duck type."

# Python "Duck Type" class F1:pass class S1 (F1): Def show (self): print ("S1.show") class S2 (F1): def show (SE LF): Print ("S2.show") def Func (obj): Print obj.show () S1_obj = S1 () func (s1_obj) s2_obj = S2 () func (s2_obj)



Viii. New and Classic classes

1. What are new and classic classes

Classic class and new class, literally can see an old a new, new inevitably contain with many functions, is also recommended after the wording, from the wording of the words, if the current class or the parent class inherits the object class, then the class is a new class, otherwise it is the classic class.

650) this.width=650; "Src=" http://mmbiz.qpic.cn/mmbiz_png/ fhujzoqe7triw2suwycgib5mcmpzlg1nejnfuiauatzzt9ibwpy9ssnxic3sgl3zfakfnludfmjlfvwmxbppo1bujq/640?wx_fmt=png& Tp=webp&wxfrom=5&wx_lazy=1 "alt=" 640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy= "/>

650) this.width=650; "Src=" http://mmbiz.qpic.cn/mmbiz_png/ Fhujzoqe7triw2suwycgib5mcmpzlg1nehdj76hejmso2qjw6svnq8ifaxorjejh5g7scibmukyola92mr5cf5dg/640?wx_fmt=png&tp =webp&wxfrom=5&wx_lazy=1 "alt=" 640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy= "/>


2. Inheritance order of new class and classic class

Class D:def Bar (self): print (' D.bar ') class C (d): Def Bar (self): print (' C.bar ') class B (d): Def Bar ( Self): print (' B.bar ') class A (B, C): Def bar (self): print (' A.bar ') a = A () A.bar ()

Python 2.X:

Classic class (Depth priority): First go to a class to find, if not in Class A, then continue to go to Class B, if there is a class B, then continue to find in Class D, if there is a class D, then continue to the class C to find, if still not found, the error

New Class ( breadth first): First go to a class to find, if not in Class A, then continue to find in class B, if there is a class B, then continue to find in Class C, if there is a Class C, then continue to find in Class D, if still not found, the error


Python 3.X:

Whether it is a classic class or a new class, the adoption is the breadth first;


Note: In the above lookup process, once found, the search process immediately interrupted, and will not continue to look for.

650) this.width=650; "Src=" http://mmbiz.qpic.cn/mmbiz_png/ fhujzoqe7triw2suwycgib5mcmpzlg1nevv6t1ibcmmpjeubjd55xywyu1iah9bhlsy37gupvrjw0ucyhiuznkwfg/640?wx_fmt=png& Tp=webp&wxfrom=5&wx_lazy=1 "alt=" 640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy= "/>


This article from "12031302" blog, declined reprint!

Python Basics-day sixth-object-oriented programming

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.