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 throughclass
Keywords:
class Student(object): pass
class
Followed by the class name, that isStudent
The 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, useobject
Class.
DefinedStudent
Class, you canStudent
Class createdStudent
Instance,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 variablebart
IsStudent
Instance, followed0x10a67a590
It is the memory address, and the address of each object is different.Student
It is a class.
You can freely bind attributes to an instance variable, suchbart
Bind onename
Attribute:
>>> 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
,score
And 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 attributesself
Becauseself
Point to the created instance itself.
With__init__
When you create an instance, you cannot enter an empty parameter.__init__
Method matching parameters,self
You 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.self
And 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. AboveStudent
Class, each instance has its ownname
Andscore
This 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, sinceStudent
The instance itself has the data. to access the data, there is no need to access the data from external functions.Student
Class internally defines the function to access data. In this way, the "data" is encapsulated. The functions that encapsulate data areStudent
Classes 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 isself
And other functions. To call a method, you only need to call it directly on the instance variable,self
No need to pass. Other parameters are passed in normally:
>>> bart.print_score()Bart Simpson: 59
In this way, we can see from the externalStudent
Class.name
Andscore
And how to print, are inStudent
Class, 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 thatStudent
Class 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_grade
The 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.