Understanding classes and instances in Python

Source: Internet
Author: User
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

The class name, which is followed by student, is usually the first word in uppercase, followed by (object), indicating which class it inherits from, and the concept of inheritance we'll say later, usually, if there is no suitable inheriting 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 + ():

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

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

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

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

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 that within the __init__ method, various properties can be bound to self, because the individual 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:

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

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. Besides, there is no difference between a class's method and a normal function, so you can still use the default, variable, and 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:

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

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 () Bart simpson:59

In this way, we look at 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 defined within the student class, 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 get_grade (self):    if Self.score >=:      return ' A '    elif self.score >=:      return ' B '    else:< C7/>return ' C '

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

>>> bart.get_grade () ' C '

Summary

The class is the template that creates the instance, and the instance is a concrete object, each instance has data that is independent of each other and does not affect each other.

method is the function that binds to the instance, and the normal function is different, the method can directly access the data of the instance;

By invoking the method on the instance, we manipulate the data inside the object directly, but we do not need to know the implementation details inside the method.

Unlike static languages, Python allows you to bind any data to an instance variable, which means that for two instance variables, although they are different instances of the same class, the variable names you have may be different:

>>> bart = Student (' Bart Simpson ', ' a ') >>> Lisa = Student (' Lisa Simpson ',) >>> bart.age = 8> ;>> bart.age8>>> Lisa.agetraceback (most recent): File "
 
  
   
  ", line 1, in 
  
   
    
     attributeerror: ' Student ' object has no attribute ' age '
  
    
   
 
  
  • 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.