Object Oriented Programming (Classes and Instances)

The most important concepts of object-oriented are the class (Class) and the instance (Instance). It must be remembered that the class is an abstract template, such as the Student class, and the instance is a specific "object" created according to the class. Each object has The same method, but the respective data may be different.

Still taking the Student class as an example, in Python, a class is defined by classkeywords:

class Student(object):
    pass

classThe class name is followed by the class name, that is Student, the class name is usually a capitalized word, followed by (object), indicating which class the class is inherited from. We will talk about the concept of inheritance later. Usually, if there is no suitable inheritance class, Just use objectclasses, which are classes that all classes will eventually inherit from.

After defining the Studentclass, you can create an instance according to the Studentclass. Creating an Studentinstance is achieved by the class name + ():

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

It can be seen that the variable bartpoints to an Studentinstance, followed by 0x10a67a590the memory address. The address of each object is different, and Studentitself is a class.

You can freely bind properties to an instance variable, for example, to bartbind a nameproperty to an instance:

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

Since a class can play the role of a template, when creating an instance, we can force some attributes that we think must be bound to be filled in. By defining a special __init__method, when an instance is created , the properties such as name, etc. are bound:score

class Student(object):

    def __init__(self, name, score):
        self.name = name
        self.score = score

 

Note: There are two underscores before and after the special method "__init__"! ! !

Note that __init__the first parameter of the method is always the selfcreated instance itself, therefore, inside the __init__method, you can bind various properties to self, because selfit points to the created instance itself.

With the __init__method, when creating an instance, you can't pass in empty parameters, you must pass in __init__the parameters that match the method, but selfyou don't need to pass it, the Python interpreter will pass the instance variable in by itself:

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

Compared with ordinary functions, functions defined in classes have only one difference, that is, the first parameter is always an instance variable self, and this parameter is not passed when calling. Other than that, class methods are no different from normal functions, so you can still use default arguments, variadic arguments, keyword arguments, and named keyword arguments.

data encapsulation

An important feature of object-oriented programming is data encapsulation. In the above Studentclass, each instance has its own nameand scorethese data. We can access this data through functions, such as printing a student's grades:

>>> def print_score(std):
...     print('%s: %s' % (std.name, std.score))
...
>>> print_score(bart)
Bart Simpson: 59

However, since Studentthe instance itself owns the data, to access the data, there is no need to access it from an external function. You can directly Studentdefine a function to access the data inside the class, thus encapsulating the "data". These functions that encapsulate data Studentare associated with the class itself, which we call class methods:

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

 

selfTo define a method, it is the same as a normal function except that the first parameter is . To call a method, you only need to call it directly on the instance variable. Except that selfyou don't need to pass it, other parameters are passed in normally:

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

In this way, when we look at the class from the outside Student, we only need to know that the sum needs to be given to create an instance name, scoreand how to print is Studentdefined inside the class. These data and logic are "encapsulated", and the call is easy. But you don't need to know the details of the internal implementation.

Another benefit of encapsulation is that you can Studentadd new methods to the 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'

Likewise, get_grademethods can be called directly on instance variables without knowing internal implementation details:

 

summary

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

A method is a function bound to an instance. Unlike ordinary functions, a method can directly access the instance's data;

By calling a method on an instance, we are directly manipulating the data inside the object without knowing the implementation details inside the method.

Unlike static languages, Python allows binding any data to instance variables, that is, for two instance variables, although they are different instances of the same class, they may have different variable names:

>>> bart = Student('Bart Simpson', 59)
>>> lisa = Student('Lisa Simpson', 87)
>>> bart.age = 8
>>> bart.age
8
>>> lisa.age
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'age'

 

 

practice coding

class Student(object):   #Define class Student 
    def  __init__ (self, name, score):   #Forcibly bind the name and score parameters to the function through init 
        self.name = name
        self.score = score
        # seif.__score =score If you want to prevent internal attributes from being accessed externally, you can add two underscores before the name of the attribute __ #In 
        Python , if the variable name of an instance starts with __, then It becomes a private variable (private), which can only be accessed internally and not externally.

    def print_score(self):
        print('{}:{}'.format(self.name,self.score))

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

bart = Student('xiaojiu', 99)
bart.print_score()
print(bart.name,bart.get_grade())

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324965987&siteId=291194637