Understanding classes and instances in Python and understanding Python instances

Source: Internet
Author: User

Understanding classes and instances in Python and understanding Python instances

The most important concepts of object-oriented are Class and Instance. You must remember that classes are abstract templates, such as Student classes, instances are specific "objects" created based on classes. Each object has the same method, but its data may be different.

Taking the Student class as an example, in Python, the class is defined by the class Keyword:

class Student(object):  pass

The class name is followed by the class name, that is, Student. The class name usually starts with an upper-case word, followed by an object, which indicates the class inherited from, we will talk about the concept of inheritance later. Normally, if there is no suitable inheritance class, we will use the object class, which is the class that all classes will ultimately inherit.

After defining the Student class, you can create a Student instance based on the Student class. The instance creation is implemented by class name +:

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

As you can see, the variable bart points to a Student object. The 0x10a67a590 is the memory address, and the address of each object is different, while the Student itself is a class.

You can freely bind attributes to an instance variable, for example, bind a name attribute to the instance bart:

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

Because the class can act as a template, You can forcibly enter some attributes that we think must be bound when creating an instance. By defining a special _ init _ method, you can bind attributes such as name and score when creating an instance:

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 indicates the created instance itself. Therefore, within the _ init _ method, you can bind various attributes to self, because self points to the created instance itself.

With the _ init _ method, you cannot input an empty parameter when creating an instance. You must input a parameter that matches the _ init _ method, but self does not need to be passed. The Python interpreter will pass the instance variables in:

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

Compared with a common function, the function defined in the class is only a little different, that is, the first parameter is always the instance variable self, and you do not need to pass this parameter when calling. In addition, class methods are no different from common functions. Therefore, you can still use default parameters, variable parameters, 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 data. We can use functions to access the data, 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 the data, to access the data, there is no need to access the data from external functions. You can directly define the function to access the data within the Student class, in this way, the "data" is encapsulated. These data encapsulation functions are associated with the Student class itself, which is called the class method:

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 that the first parameter is self, it is the same as that of a common function. To call a method, you only need to call the instance variable directly. Except for self, other parameters are passed in normally:

>>> bart.print_score()Bart Simpson: 59

In this way, we can look at the Student class from the external, we only need to know that the name and score need to be given to create an instance, and how to print them is defined internally in the Student class, the data and logic are "encapsulated", so it is easy to call, but you do not need to know the details of the internal implementation.

Another advantage of encapsulation is that you can add new methods to the Student class, such as get_grade:

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

Similarly, the get_grade method can be called directly on instance variables without knowing the internal implementation details:

>>> bart.get_grade()'C'

Summary

A class is a template for creating an instance, and an instance is a specific object. The data of each instance is independent of each other and does not affect each other;

The method is the function bound to the instance. Unlike the common function, the method can directly access the instance data;

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

Different from static languages, Python allows you to bind any data to instance variables. That is to say, for both instance variables, although they are different instances of the same class, their variable names may be different:

>>> bart = Student('Bart Simpson', 59)>>> lisa = Student('Lisa Simpson', 87)>>> bart.age = 8>>> bart.age8>>> lisa.ageTraceback (most recent call last): File "<stdin>", line 1, in <module>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.