Python Object-oriented

Source: Internet
Author: User

Object-oriented programming--object oriented programming, short for OOP, is a programming idea. OOP takes objects as the basic unit of a program, and an object contains functions for data and manipulating data.

Process-oriented programming treats a computer program as a set of commands, which is the sequential execution of a set of functions. In order to simplify the program design, the process will continue to cut the function into sub-function, that is, the large function by cutting into small block function to reduce the complexity of the system.

Object-oriented programming treats a computer program as a set of objects, and each object can receive messages from other objects and process them, and the execution of a computer program is a series of messages passing between objects.

In Python, everything is object, including all data types, and you can customize the object yourself. The custom object data type is the concept of object-oriented classes (class).

For example, take a visual look at the difference between a process-oriented and object-oriented implementation of the same function

For example, we have to deal with a student's score table, the process will do this, first with a dict to accept students ' achievements

STD1 = {' name ': ' Michael ', ' score ': 98}STD2 = {' name ': ' Bob ', ' Score ': 81}

And then we're going to print the student scores

def print_score (STD):    print ('%s:%s '% (std[' name '], std[' score '))

If we adopt the object-oriented program design idea, we prefer not to think about the program's execution flow, but this Student data type should be treated as an object, which owns the object name and both score properties. If you want to print a student's score, you first have to create the corresponding object for the student, and then send a message to the object to print_score let the object print its own data.

Class Student (object):    def __init__ (self, Name, score):        self.name = name        Self.score = Score    def print_ Score (self):        print ('%s:%s '% (Self.name, Self.score))

Sending a message to an object is actually a call to the object corresponding to the associated function, which we call the object method

Bart = Student (' Bart Simpson ', i) Lisa = Student (' Lisa Simpson ',) Bart.print_score () Lisa.print_score ()

Classes (Class) and instances (Instance)

In the above example student is a class, and Bart,lisa is a concrete student instance.

Keep in mind that classes are abstract templates, such as the student class, and instances are specific "objects" that are created from the class, each with the same method, but the data may be different.

Defining a class in Python is defined in the Class keyword:

Class Student (object):      Pass

class names are followed by classes, that is, the Student class name is usually the beginning of the word, followed by the class is the class (object) from which to inherit, the concept of inheritance we are not anxious, usually, if there is no appropriate inheritance class, use the Class object , which is the class that all classes will eventually inherit.

Of course, we might see the following definition:

Class Student:     Pass

This is the classic class, the above is called the new class, in the Python3 use the modern class, the default does not have to display the write object, but the specification is best to write.

Once you have defined the Student class, you can Student create Student an instance from the class by using the class name + () to create the instance:

>>> Bart = Student () >>> bart<__main__. Student object at 0x10a67a590>>>> student<class ' __main__. Student ' >

The variable Bart points to an instance of a student, and the latter 0x10a67a590 is the memory address, each object has a different memory address, and student itself is a class.

We are free to bind an attribute to an instance variable, such as a property that binds Bart to a name:

>>> bart.name = ' Bart Simpson ' >>> bart.name ' Bart Simpson '

Because the class acts as a template, we can force the attributes that we think we need to write when we create the class. By defining a __init__ method, you can tie the Name,score up:

Class Student (object):    def __init__ (self, Name, score):        self.name = name        Self.score = Score

Notice that the __init__ first parameter of the method is always the one that self represents the created instance itself, so within the __init__ method, you can bind various properties to it self , because self it points to the created instance itself.

With the __init__ method, when you create an instance, you cannot pass in an empty argument, you must pass in a __init__ parameter that matches the method, but it self does not need to be passed, and the Python interpreter will pass the instance variable in itself:

>>> bart = Student (' Bart Simpson ', ') >>> bart.name ' Bart Simpson ' >>> bart.score59

A function defined in a class is only a little different than a normal function, that is, the first argument is always an self instance variable, and when called, it is not passed. In addition, there is no difference between a class method and a normal function, so you can still use default parameters, variable arguments, keyword arguments, and named keyword parameters.

Package

One of the most important features of object-oriented programming is encapsulation, Student where each instance has name its own and score This data in the class above. We can access this data through functions, such as printing a student's score:

>>> def print_score (std):     ... Print ('%s:%s '% (Std.name, std.score)) ...>>> Print_score (Bart) Bart simpson:59

But since the student instance itself already has this data, there is no need to access the data from an external function, and we can define the function that accesses the data directly inside the student, thus encapsulating the data. The functions of these encapsulated data are also associated with the student class itself, so we also call it the method of the class :

Class Student (object):    def __init__ (self, Name, score):        self.name = name        Self.score = Score    def Print_score (self):        print ('%s:%s '% (Self.name, Self.score))

To define a method, except for the first argument self , the other is the same as the normal function. To invoke a method, just call it directly on the instance variable, except self that it does not pass, and other parameters are passed in normally:

>>> Bart.print_score () Bart simpson:59

In Student name score This way, we look at the class from the outside, just need to know that the creation of the instance needs to give and, and how to print, are defined within the class, Student The data and logic are "encapsulated", and the invocation is easy, but without knowing the details of the internal implementation.

Another benefit of encapsulation is the ability Student to add new methods to the class get_grade , such as:

Class Student (object):    ...    def get_grade (self):        if Self.score >=:            return ' A '        elif self.score >=:            return ' B '        else:            return ' C '

Similarly, get_grade The method can be called directly on an instance variable without needing to know the internal implementation details:

>>> bart.get_grade () ' C '

So, encapsulation is actually to hide the object's attributes and implementation details, not allow external direct access, expose the method, and let the method manipulate or access these properties.

Access restrictions

However, from the previous definition of the student class, the external code is free to modify the properties of an instance name score :

>>> bart = Student (' Bart Simpson ', 98) >>> bart.score98>>> Bart.score = 59>>> Bart.score59

If you want the internal properties to be inaccessible externally, you can add the name of the property with two underscores __ , and in Python, the variable name of the instance __ becomes a private variable (private), which can only be accessed internally and cannot be accessed externally, so We changed the Student class:

Class Student (object):    def __init__ (self, Name, score):        self.__name = name        Self.__score = Score    def Print_score (self):        print ('%s:%s '% (Self.__name, Self.__score))

After the change, for external code, there is no change, but it has been unable to access from outside 实例变量.__name and 实例变量.__score :

>>> bart = Student (' Bart Simpson ', 98) >>> Bart.__nametraceback (most recent call last):  File "<s Tdin> ", line 1, in <module>attributeerror: ' Student ' object have no attribute ' __name '

This ensures that external code cannot arbitrarily modify the state inside the object, so that the code is more robust through access-restricted protection.

is an instance variable that starts with a double underscore not necessarily externally accessible? The answer is no:

>>> bart._student__name ' Bart Simpson '

In fact, there is no private property in Python, ' _ ' tells others that I am a private property, you do not access, and does not have a syntax above the restrictions, or can be accessed by external code, ' __ ' Although can not be accessed, but in fact, Python played a small smart, the property name to change, such as. __name replaced it. Student.__name.

All in all, Python itself has no mechanism to stop you from doing bad things, all on your own.

There is also a wrong notation:

>>> bart = Student (' Bart Simpson ', 98) >>> bart.get_name () ' Bart Simpson ' >>> bart.__name = ' New Name ' # Set the __name variable! >>> bart.__name ' New name '

The surface is modified successfully, actually not, because actually this __name variable and class inside the __name variable is not a variable! The internal __name variables have been automatically changed by the Python interpreter _Student__name , and the external code bart adds a new __name variable.

Inherited

In OOP programming, when we define a class, we can inherit from an existing class, and the new class is called a subclass (subclass), and the inherited class is called the base class, the parent class, or the superclass (base-Class, Super-Class).

For example, we write a animal class and write a talk method:

Class Animal (object):    def Talk (self):        print (' Animal is talking ')

Then I wrote a dog and cat class inheriting the animal class:

Class Dog (Animal):    passclass Cat (Animal):    Pass

The best thing about inheritance is that it implements the function of the parent class:

Dog = Dog () cat = Cat () Dog.talk () Cat.talk ()

The results of the operation are as follows: Animal is Talkinganimal is talking

The second benefit of inheritance requires a little improvement in our code. Supposedly, dog and cat should be ' dog is talking ' and ' cat is talking ' at Talk () to make the following modifications:

Class Dog (Animal):    def Talk (self):        print (' Dog was talking ') class Cat (Animal):    def Talk (self):        print (' Cat is talking ')

Run the results again as follows:

Dog is Talkingcat is talking

Polymorphic

Polymorphism can be said to be a benefit of inheritance: when both the subclass and the parent class have the same talk () method, we say that the sub-class's Talking () overwrites the parent's talk (), which always calls the subclass when the code is running.

To understand the benefits of polymorphism, you also need to write an example of a function that takes a variable of type animal:

def talk_twice (animal):
Animal.talk ()
Animal.talk ()

When we pass in the dog and cat instances, we print out:

Dog = Dog () cat = Cat () animal.talk_twice (dog) Animal.talk_twice (cat) Run result dog is Talkingdog are Talkingcat is Talkingcat is Tal King

The advantage is that the next time I define a class pig inheritance animal, you do not need to modify Talk_twice () to send an instance of pig into it.

Python does not support polymorphism or polymorphism is basically not used, Python supports the ' duck model ', "as long as the ducks like walking, barking like ducks, are ducks":

Class Car (object):    def Talk (self):        print (' car is talking ')

Then call Talk_twice ():

Animal.talk_twice (CAR)

Output Result:

Car is Talkingcar is talking

For dynamic languages such as Python, the incoming type is not necessarily required Animal . We just need to make sure that the incoming object has one run() way to go.

Python Object-oriented

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.