Classes and instances
1, Class: There are properties there are methods that are classes. Here is the Student 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)) def get_grade (self): if self.score >= 90: return ' A ' elif self.score >= 60 : return ' B ' else: return ' C '
2, example (instance): the specific object. Here's how the class student is created:
Vincent = Student (' Vincent ', +) Lisa = Student (' Lisa ', 80)
Once you have defined the Student class, you can use this class to create concrete instances, such as Vincent,lisa.
When creating an instance, you must fill in the relevant attributes. By defining the __init__ method, the Name,score property is bound when the instance is created. Each time you create an instance, Python automatically calls the __init__ method, which is also a constructor. Its first argument is always self, and it does not need to be passed in, and Python automatically passes in the instance variable.
def __init__ (self, Name, score): Self.name = name Self.score = Score Vincent = Student (' Vincent ', +) Lisa = Stud ENT (' Lisa ', 80)
Encapsulation of data
Another important feature of object-oriented is the encapsulation of data. In the above instance of the Student class, each instance has its own name and score data. We can access this data through functions, such as print scores:
def print_score (self): print ('%s:%s '% (Self.name,self.score))
sinceStudent
The instance itself has this data, to access the data, there is no need to access from the outside functions, you can directly in theStudent
The inside of the class defines the function that accesses the data, so that the "data" is encapsulated. The functions of these encapsulated data are andStudent
The class itself is associated, and we call it the method of the class.
Python Learning: Object-oriented (OOP)