Python object-oriented and instances

Source: Internet
Author: User
This article to share the content is about the Python object-oriented and other instances, has a certain reference value, the need for friends can refer to

Classes and instances


Object-oriented concepts are classes (class) and instances (Instance), and it is important to keep in mind that classes are abstract templates, such as student classes, and instances are specific "objects" that are created from classes, each with the same method, but the data may be different for each object.

Still take the student class as an example, in Python, the definition class is through the Class keyword:

Class Student (object):   Pass

Class is immediately followed by the name, that is, student, the class name is usually the beginning of the word, followed by (object), indicating the class is inherited from the class, the concept of inheritance we later, usually, if there is no appropriate inheritance class, use the object class, This is the class that all classes will eventually inherit.

Once you have defined the Student class, you can create an instance of student based on the student class, which is implemented by the class name + ():

Class Student (object):   Passbart = Student () print (BART) print (Student)
<__main__. Student object at 0x000001a9412a47b8><class ' __main__. Student ' >

As you can see, the variable Bart is pointing to an instance of student, and the latter 0x000001a9412a47b8 is the memory address, each object has a different address, and student itself is a class.

You are free to bind attributes to an instance variable, for example, Bart binds a Name property:

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)) Bart = Student (' Boyuan Zhou ', +) Lisa = Student (' Maomao ', 100) Bart.name= ' Jeff ' Print (Bart.name)
Jeff

Because a class can act as a template, you can force a number of attributes that we think must be bound to be filled in when creating an instance. By defining a special __init__ method, when creating an instance, bind the attributes such as Name,score:

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

Note that the first parameter of the __init__ method is always self, which represents the created instance itself, so within the __init__ method, you can bind the various properties to self, because 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 parameter that matches the __init__ method, but self does not need to be passed, and the Python interpreter will pass the instance variable in itself:

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)) Bart = Student (' Boyuan Zhou ', +) Lisa = Student (' Maomao ', 100) Bart.name= ' Jeff ' Print (bart.name) print (Bart.score)
jeff100

A function defined in a class is only a bit different than a normal function, which is that the first argument is always the instance variable self and, when called, does not pass the argument. 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.

Data encapsulation

An important feature of object-oriented programming is data encapsulation. In the student class above, each instance has its own name and score the data. We can access this data through functions, such as printing a student's score

>>> std1 = {' name ': ' Jeff ', ' score ':100}>>> std2 = {' name ': ' Xin ', ' score ':0}>>> def Print_ Score (STD):     ... Print ('%s:%s '% (std[' name '],std[' score ')) ...>>> Print_score (STD1) jeff:100>>> Print_score (STD2) xin:0

However, since the student instance itself has this data, it is not necessary to access the data from outside the function to access, you can directly within the student class to define the function to access the data, so that the "data" to encapsulate it. The functions of these encapsulated data are associated with the student class itself, and we 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, the other one is the same as the normal function except that the first argument is self. To invoke a method, just call it directly on the instance variable, except that self does not pass, and other parameters are passed in normally:

Bart.print_score () jeff:100

In this way, we see the student class from the outside, just need to know that the creation of the instance needs to give name and score, and how to print, is the student class of internal definition, the data and logic is "encapsulated", the call is easy, but do not know the details of the internal implementation.

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

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))    def get_grade (self):        if Self.score >=90:            Return ' A '        elif self.score>=600:            return  ' B '        else:            return  ' C ' Bart = Student (' Boyuan Zhou ', +) Lisa = Student (' Maomao ', +) bart.name= ' Jeff ' Bart.print_score () print (Bart.get_grade ())
jeff:100a

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.