Python Learning Notes (vii): Object-oriented Programming, class

Source: Internet
Author: User
Tags sleep function

First, object-oriented programming

Object-oriented--object oriented programming, short for OOP, is a programming idea. Before we talk about object-oriented, let's talk about what is the programming paradigm, the programming paradigm, and the way you go about programming, to implement a function. For example, you have to cook, you can use an induction cooker, or you can use a gas stove. The different programming paradigms essentially represent the different problem-solving ideas taken for various types of tasks, and the two most important programming paradigms are process-oriented programming and object-oriented programming.

Referring to object-oriented, we have to mention another kind of programming idea, process-oriented, what is the process-oriented idea is to put a project, a thing in a certain order, from beginning to end, do what first, what to do, all the way down to the finish. This idea is better understood, in fact, it is also a person's way of doing things, our previous programming ideas are also using this idea. This kind of programming thought, as long as there is a step in front of the change, then the back will be changed, the latter is more trouble to maintain, such a programming idea, we write some simple small program, only execute once script can be used. Object oriented, object-oriented thinking is to divide a project, a thing into smaller projects, or into a smaller part, each part responsible for what aspects of the function, and finally by the combination of these parts become a whole. This kind of thought is more suitable for many people's Division of labor, like a large organ, divided into various departments, each department is responsible for a certain function, each department can give full play to their own characteristics, as long as a certain premise on the line.

For example: For example, just said a large organ, to do a certain project, from the process-oriented thinking, it should be this analysis, first how, then how, finally how. How the first should be done, how the second should be done, and so on. When each step is completed, the project is completed. And the object-oriented thought should be like this, the project is composed of several parts, we will do a division, set up a department to do a part of the function of another department to do another part. Departments can not understand other departments, as long as the completion of their own part of the matter is OK.

Second, object-oriented characteristics

Classes: Class

class, compared to the real world, is a kind, a model.

A class is an abstraction, a blueprint, a prototype for a class of objects that have the same properties.

The properties of these objects (variables (data)) and common methods are defined in the class.

Objects: Object

Object, that is, the concrete thing created by the model.

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 everyone, each person refers to the specific object, people and people before there is a common, but also different.

Instantiation:

Initializes a class, creating an object. The process of turning a class into a concrete object is called instantiation.

Packaging:

The implementation details of some functions are not exposed, the assignment of data in the class, the internal invocation is transparent to the external user, which makes the class become a capsule or container, in which the bread implies the data and methods of the class.

For example, create a person, you put his body inside of what heart spleen lungs and kidneys are sealed up, other people can not see, you directly find this person.

Inherited:

A class can derive a subclass, and the properties, methods defined in the parent class automatically inherit the quilt class. For example, you inherit your father's surname.

Multi-Inheritance in Python3 is the breadth first, and the multi-inheritance of classical class in Python2 is the depth first, and the multi-inheritance of the new class is in the breadth first.

Inheritance is for the reuse of code

Polymorphic:

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 is a manifestation of abstraction that abstracts out the common denominator of a series of specific things and then, through this abstraction, dialogues with different specific things.

An interface, a variety of implementations.

Iii. Object-oriented benefits

For beginners of programming language, OOP is not a very easy to understand programming, although everyone according to the teacher know that the three main features of OOP is inheritance, encapsulation, polymorphism, and everyone knows how to define classes, methods and other object-oriented common syntax, but one to really write programs, Still a lot of people like to use functional programming to write code, especially beginners, it is easy to fall into a dilemma is "I know object-oriented, I will write classes, but I still do not find that after the use of object-oriented, to our program development efficiency or other aspects of what benefits, Because I can use functional programming to reduce duplication of code and do the program extensible, why also use object-oriented? "For this, I personally think the reason should be because you do not fully understand the benefits of object-oriented."

No matter what the form of programming, we have to clearly remember the following principles:

Writing duplicate code is a very bad low-level behavior.

The code you write needs to change frequently.

The development of a formal program with the kind of writing a run-time throw the small script a very big difference is that your code always need to constantly change, not to modify the bug is to add new features, etc., so in order to facilitate program modification and extension, you write code must follow easy-to-read, easy to change the principle (professional data called good readability, Easy to expand).

If you copy a piece of the same code, paste it into the program in a number of places to implement the application in various places, this function, then you can change this function later, you need to change the program in many places, this way of writing the program is problematic, because if you accidentally missed a place not changed, That could lead to problems with the entire program running. So we know that in development we must try to avoid writing duplicate code, otherwise it is equivalent to digging holes for ourselves.

Fortunately, the appearance of functions can help us to easily solve the problem of duplicate code, for the function that needs to be repeated calls, only need to write it into a function, and then call the function name directly in each place of the program, and when it is necessary to modify the function, just change the function code, and then the whole program is updated.

In fact, the main role of OOP programming is to make your code modification and extension of the more easily, then the small white to ask, since the function can achieve this demand, but also the OOP dry yarn use it? Hehe, saying this is like, ancient times, people fight to kill all with knives, later came out of the gun, its main function with the same knife, but also kill, and then small White asked, since the knife can kill, that also gun dry yarn, haha, obviously, because the gun can be better faster and easier to kill. The main difference between functional programming and OOP is that OOP can make programs easier to scale and change.

Iv. class

Some concepts:

Property: A property is a variable within a class, with a class variable and an instance variable, a class variable is a class at the time it is defined, and an instance variable is a variable that is generated when instantiated. This can be understood as the person is a class, his name, age, sex is its attributes.

Method: The method is the function of the class, which is defined in the class function, it implements a function, for example, people have sleep function.

Constructor: What is a constructor, which is the initialization of a class when it is instantiated, such as a person, when you build a car, it has to have color, model, and so on.

Destructors: Destructors are some of the operations that this instance does when it is destroyed.

To define a class:

Define class using class keyword, class name generally we develop the first letter to capitalize. There are classic classes and new classes in Python, and they are not different in Python3, in which the classic class is depth-first in multiple inheritance, and the new class is breadth-first. The unification in Python3 is the breadth first, and this later says in succession.

            classPerson (object):#define the class, this is the new classNationality =' China' #Class Properties                    def __init__(self,name,sex):#constructor FunctionSelf.name = Name#Instance PropertiesSelf.sex =Sexdef __del__(self):# Destructors                        Print('This is a destructor.')                    defInfo ():#Method                           Print('name is%s sex is%s'%(self.name,self.sex))classPerson1:#Define class, this is the classic classNationality =' China' #Class Properties                    def __init__(self,name,sex):#constructor FunctionSelf.name = Name#Instance PropertiesSelf.sex =SexdefInfo ():#Method                           Print('name is%s sex is%s'%(self.name,self.sex)) Niuniu= Person ('Beef Cattle','male')#instantiation, because the above constructor specifies that name and sex must be passed, so when you instantiate it, name and sex are passed in.Niuniu.info ()#Invoking instance methods

Inherited:

               classF (object):" "This is the parent class ." "                    def __init__(self,name,sex): Self.name=name Self.sex=SexdefInfo ():#Method                        Print('name is%s sex is%s'%(self.name,self.sex))classS (F):#inherit F this class                    PassS1= S ('Beef Cattle','male')#instantiating subclassesS1.info ()#because the parent class is inherited, the method of the parent class hasthat if there is a method in the parent class, there is a subclass inside, but the subclass wants to rewrite the parent class method, add the new function to write the following:classTest ():def __init__(self,name): Self.name=nameclasstest1 (test):def __init__(self,name,age):#test.__init__ (self,name) #修改父类的方法, this is the classic class inside the wordingSuper (Test1,self).__init__(name)#like the effect above, this is the style of the new class.Self.name =name Self.age=Age Test1 ('name',' Age') Multiple inheritance, the above is written in single inheritance, Python also supports multiple inheritance, multiple inheritance is inherited from multiple parents, in the Python3 multiple inheritance is breadth first, in Python2 a little different, the classic class is depth first, the new class is breadth first. classA:defSay (self):Print('A')                classB (A):#Pass                    defSay (self):Print('B')                classC (A):Pass                    #def Say (self):                    #print (' C ')                classD (c,b):Passs=D () S.say ()

Polymorphic: Python does not directly support polymorphism, and it can be done in other ways to achieve polymorphism. The following example can be implemented an interface, a variety of implementations, for the following cry method, regardless of what you pass in the object, as long as there is a cry method, will call its cry method, do not have to call one by one.

                                classAnimal (object):" "Parent Class" "                    def __init__(self,name): Self.name=nameclassDog (Animal):" "dogs, methods of barking" "                    defCry (self):Print('Dog [%s] Wang Woo'%self.name)classCat (Animal):" "Cat, a method of barking" "                    defCry (self):Print('Cat [%s] Mew Meow'%self.name)defCry (obj):" "define a function to invoke the Cry method of the passed in instance" "obj.cry () D1= Dog ('Rhubarb')#instantiation of the dogD2 = Dog ('Xiao Huang')#instantiation of the dogC1 = Cat ('Small white')#Instantiate a catC2 = Cat ('Little Black')#Instantiate a catCry (D1)#pass the object D1 in .Cry (D2)#pass the object D2 in .OBJS = [D1,D2,C1,C2]#Put all the objects instantiated above into a list                 forObjinchOBJS:#Circular Unified InvocationCry (obj)

Private methods, private properties:

What is private, private is only accessible within the class, cannot be accessed and invoked after instantiation, has private methods and private properties. Private to the variable name or function name before the "__" two underline, in fact, through the private to achieve encapsulation.

                classDog (object):__type='Dog'#Private Properties                    defCry (self): self.__test()#Calling Private Methods                        Print('Private Property%s'%self.__type)                        Print('Dog [%s] Wang Woo'%self.name)def __test(self):#Private MethodsSelf.name ='Test'#D =D () d.cry ()#Normal can callD.__type#error, because it is a private property, cannot be accessed outsideD.__test()#error, because it is a private method, cannot be accessed outside

Static Methods and class methods:

       classStu (object): Country=' China'#class Variables            def __init__(self,name): Self.name=name @staticmethod#The static method, which has nothing to do with the class itself, is equivalent to defining a method within the class .            defsay ():Print('XXX') @classmethod#The static method, unlike the class method, is that it can use a class variable and must pass a value that represents the class            defHello (CLS):Print(cls.country)defhi (self):#This is an example method .                Print(self.name) T= Stu ('name') Stu.hello () Stu.say () T.hi () T.say () T.hello ()

Python Learning Notes (vii): Object-oriented Programming, class

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.