Python basics-Object-oriented programming

Source: Internet
Author: User

Object-Oriented Programming

OOP programming is the use of "class" and "object" to create a variety of models to achieve a real-world description, the use of object-oriented programming because it can make the maintenance and extension of the program easier, and can greatly improve the efficiency of program development, in addition, An object-oriented program can make it easier for people to understand your code logic and make team development easier.

Several core features of object-oriented are as follows

Class
A class is an abstraction, a blueprint, a prototype for a class of objects that have the same properties. The properties of these objects are defined in the class (variables (data)), common methods

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

Encapsulation Package
The assignment of data in a class, internal invocation is transparent to external users, which makes the class A capsule or container in which the data and methods of the class are contained.

Inheritance inheritance
A class can derive subclasses, properties, methods defined in the parent class, automatic quilt class inheritance

Polymorphism Polymorphism
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 invokes the method is already determined before it is compiled, and the object pointed to by the reference can be dynamically bound during run time

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 reason, I personally think that because you do not fully understand the benefits of object-oriented, I will write a primer on the object-oriented article, I hope to help you understand and use object-oriented programming. No matter what the form of programming, we have to clearly remember the following principles:
    1. Writing duplicate code is a very bad low-level behavior.
    2. 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 invoke the function in various parts of the program, then you can change the function in the future, you need to change the program in a number of places, the way to write 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. syntax of the classexplained in the following code
1 classDog (object):2     def __init__(self,name,dog_type):3         """Constructors , or constructors, can also be called initialization methods"""4Self. Nmae = Name#equivalent to D. Name = Name5Self. Dog_type =Dog_type6 7     defSayhi (self):#methods of the class8         Print('You be a%s dog,your name is%s'%(self.) Dog_type,self. Nmae))9     defEat (self):#methods of the classTen         Pass OneD = Dog ('Xiaowang','BEIJING-Pakistan')#equivalent to dog (d, ' Xiaowang ', ' boe '), self: The object generated after instantiation is called an instance, where self refers to an instance of the current class, that is, D.  A """' Xiaowang, JD These two parameters are parameters that are worn to the constructor of the class '""" -D.sayhi ()#equivalent to D.sayhi (d) -  the Output: -You is a dog,your name isXiaowang

Above d = Dog (' Xiaowang ', ' boe '), D is an instance of the class Dog instantiation, Print (dog), print (d), the output is as follows:

<class'__main__. Dog'> # even if not instantiated, the dog class itself is already in memory in the <__main__. Dog object at 0x0000000000dea080> #d就是Dog实例化后的对象, there is also memory inside

Example:

1 classRole (object):2     def __init__(Self,name,weapon,life_value = 100,money = 15000):3Self.name =name4Self.weapon =Weapon5Self.life_value =Life_value6Self.money = Money7 8     defShot (self):9         Print('%s is shooting'%self.name)Ten     defGot_shot (self): One         Print("Ah...,i got shot ...") A     defBuy_gun (self,gun_name): -         Print('%s bought%s'%(self.name,gun_name)) -Self.weapon = Gun_name#Replace the original weapon the  -D1 = Role ('Cui','AK47') -D2 = Role ('Wang','B51') -D1.buy_gun ('B21') + Print(D1.weapon) -  + Output: A Cui bought B21 atB21
View Code

Private properties and Public properties

A private property can only be called within a class, when defined, Self.__name = name, preceded by two underscores.

classRole (object):def __init__(Self,name,weapon,life_value = 100,money = 15000): Self.name=name Self.weapon=Weapon Self.life_value=Life_value Self. Money=Money self .__high= 175#define a private property    defShot (self):Print('%s is shooting'%self.name)Print(self.)__high)#internal can be called    defGot_shot (self):Print("Ah...,i got shot ...")    defBuy_gun (self,gun_name):Print('%s bought%s'%(self.name,gun_name)) Self.weapon= Gun_name#Replace the original weaponD1= Role ('Cui','AK47') D2= Role ('Wang','B51') D1.shot ()Print(D1.__high)#Call Erroroutput: Traceback (most recent call last): Cui isShooting File"d:/script/p_script/python_cq/temp.py", line 25,inch<module>Print(D1.__high)175Attributeerror:'Role'object has no attribute'__high'
View Code

But if you must call the private properties of the class externally, you can

Print (D1._role__high)

What if you want to return the value of a private property?

classRole (object):def __init__(Self,name,weapon,life_value = 100,money = 15000): Self.name=name Self.weapon=Weapon Self.life_value=Life_value Self. Money=Money self .__high= 175#define a private property    defShot (self):Print('%s is shooting'%self.name)Print(self.)__high)#internal can be called    defGot_shot (self):Print("Ah...,i got shot ...")    defBuy_gun (self,gun_name):Print('%s bought%s'%(self.name,gun_name)) Self.weapon= Gun_name#Replace the original weapon    defHigh (self):#provides a read-only interface for external access to private properties        returnSelf.__highD1= Role ('Cui','AK47') D2= Role ('Wang','B51') D1.shot ()Print(D1._role__high)Print(D1.high ()) Output: Cui isShooting175175175
View Code

Public properties

  

Python basics-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.