Basic Python-classes and instances, basic python instances

Source: Internet
Author: User

Basic Python-classes and instances, basic python instances

The following is an official tutorial from Liao Xuefeng. Thank you very much!

Class and instance

 

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 throughclassKeywords:

class Student(object):    pass

classFollowed by the class name, that isStudentThe class name is usually a word starting with an upper case, followed(object)Indicates the class from which the class is inherited. We will talk about the concept of inheritance later. Normally, if there is no suitable inheritance class, useobjectClass.

DefinedStudentClass, you canStudentClass createdStudentInstance,Instance creation is implemented by class name + ()Of:

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

You can see that the variablebartIsStudentInstance, followed0x10a67a590It is the memory address, and the address of each object is different.StudentIt is a class.

You can freely bind attributes to an instance variable, suchbartBind onenameAttribute:

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

BecauseClass can act as a templateTherefore, you can forcibly enter some attributes that we think must be bound when creating an instance. By defining a special__init__When creating an instancename,scoreAnd other attributes:

Class Student (object): def _ init _ (self, name, score): # Note: special method"Init"There are two underlines !!! Self. name = name self. score = score

Notes__init__The first parameter of the method is alwaysself, Indicates the created instance. Therefore__init__Internal method, you can bind various attributesselfBecauseselfPoint to the created instance itself.

With__init__When you create an instance, you cannot enter an empty parameter.__init__Method matching parameters,selfYou do not need to upload the instance variables. The Python interpreter will upload the instance variables as follows:

>>> 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 an instance variable.selfAnd you do not need to pass this parameter during the call. In addition, class methods are no different from common functions. Therefore, you can still use default parameters, variable parameters, keyword parameters, and named keyword parameters.

 

Data encapsulation

An important feature of object-oriented programming is Data encapsulation. AboveStudentClass, each instance has its ownnameAndscoreThis 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, sinceStudentThe instance itself has the data. to access the data, there is no need to access the data from external functions.StudentClass internally defines the function to access data. In this way, the "data" is encapsulated. The functions that encapsulate data areStudentClasses are associated. We call them the methods of classes:

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))

YesDefine a methodExcept that the first parameter isselfAnd other functions. To call a method, you only need to call it directly on the instance variable,selfNo need to pass. Other parameters are passed in normally:

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

In this way, we can see from the externalStudentClass.nameAndscoreAnd how to print, are inStudentClass, the data and logic are "encapsulated", and it is easy to call, but you do not need to know the details of the internal implementation.

Another advantage of encapsulation is thatStudentClass to add new methods, suchget_grade:

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

Similarly,get_gradeThe method can be called directly on instance variables without the need to know 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'

The age variable is added to the bart instance to obtain the bart. age. The age variable is not added to the lisa instance, so lisa. age cannot be obtained.

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.