_ Python object-oriented classes and instances (a)

The most important object-oriented concepts is the class (Class) and instance (Instance), must bear in mind the class is abstract template, such as the Student class, and instance is created out of a class based on a specific "object", each object has in the same manner, but the respective data may be different.

Still the Student class, for example, in Python, classes are defined by classkeyword:

class Student(object):
    pass

classIs immediately followed by the class name, ie Student, the class name is usually the beginning of the word capitalized, followed by (object)showing the class which is inherited from the class down, the concept of inheritance behind us repeat that, generally, if there is no suitable class inheritance, on the use of objectclass, which is all classes eventually inherited class.

Defined the Studentclass, you can Studenttype to create Studentinstances, create an instance of the class name + () achieved by:

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

We can see, the variable bartis a pointer to the Studentinstance of the latter 0x10a67a590is the memory address, the address of each object is not the same, but Studentin itself is a class.

Free to give an instance variable binding properties, such as, for example bartbind a nameproperty:

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

Since the class can act as a template, so you can create an instance of the time, we believe that some of the property must be bound mandatory to fill in. By defining a special __init__way when creating instances, put name, scoreand so tied to property:

class Student(object):

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

Noted that the __init__first argument is always self, in itself represented by an instance is created, therefore, the __init__internal methods, we can put all kinds of property is bound to self, because selfit points to create an instance of itself.

With the __init__method, create an instance in time, you can not pass a null parameter, you must pass the __init__parameter matching method, but selfdo not need to pass, Python interpreter himself will pass in an instance variable:

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

And compared to normal function, only a little different in function defined in the class, is the first argument is always an instance variable self, and when you call, do not pass this parameter. In addition, the methods of the class and normal function is no different, so you can still use the default parameters, variable parameters, keywords and named keyword arguments.

Data encapsulation

An important feature of object-oriented programming is the data package. In the above Studentclass, each instance has its own on nameand scoredata. We can access these data through functions, such as printing a student's achievement:

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

However, since Studentexamples of the data itself has to access this data, there is no need to access the function from the outside, can be directly Studentdefined within the class of functions of the data access, otherwise, then "data" to the encapsulate. These functions are encapsulated data and Studentthe class itself are linked together, 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))

To define a method, in addition to the first parameter is selfoutside, and the other normal functions. To call a method, you only need to call directly on the instance variables, in addition to selfnot pass, the other normal parameters passed in:

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

As a result, we see from outside the Studentclass, you just need to know, given the need to create an instance nameand score, and how to print, are Studentwithin the class definition, these data and logic is "packaged" up call is easy, but we do not know the details of the internal implementation.

Another advantage of encapsulation is to Studentadd a new class of methods, such as get_grade:

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

Similarly, the get_grademethod can be called directly on the instance variables do not need to know the internal implementation details:

lass Student(object):
def __init__(self, name, score):
self.name = name
self.score = score

def get_grade(self):
if self.score >= 90:
return 'A'
elif self.score >= 60:
return 'B'
else:
return 'C'
lisa = Student('Lisa', 99) bart = Student('Bart', 59) print(lisa.name, lisa.get_grade()) print(bart.name, bart.get_grade())

summary

Create an instance of the class is a template, and a specific example is a object, each instance has a data are independent of each other, independently of each other;

The method is different from Example binding function and a normal function, the method may directly access the data instance;

By calling the method on an instance, we can directly manipulate the data inside an object, but without knowing the internal implementation details of the method.

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

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

  

 

Guess you like

Origin www.cnblogs.com/yzg-14/p/12184613.html