Home  >  Article  >  Backend Development  >  Python object-oriented classes and examples

Python object-oriented classes and examples

不言
不言Original
2018-04-14 10:16:331762browse

The content shared with you in this article is about Python object-oriented classes and examples, which has certain reference value. Friends in need can refer to

Classes and Examples


The most important concepts of object-oriented are classes and instances. It must be remembered that classes are abstract templates, such as the Student class, while instances are specific " Object", each object has the same methods, but their data may be different.

Still taking the Student class as an example, in Python, defining a class is through the class keyword:

class Student(object):
   pass

class is followed by the class name, which is Student. The class name usually starts with a capital. The word followed by (object) indicates which class the class is inherited from. We will talk about the concept of inheritance later. Usually, if there is no suitable inheritance class, the object class is used. This is what all classes will eventually do. Inherited classes.

After defining the Student class, you can create an instance of Student based on the Student class. Creating an instance is achieved through the class name ():

class Student(object):
   pass

bart = Student()
print(bart)
print(Student)
<__main__.Student object at 0x000001A9412A47B8>
<class &#39;__main__.Student&#39;>

As you can see, the variable bart points to An instance of Student, the following 0x000001A9412A47B8 is the memory address, the address of each object is different, and Student itself is a class.

You can freely bind attributes to an instance variable. For example, bind a name attribute to the instance bart:

class Student(object):
    def __init__(self,name,score):
        self.name = name
        self.score = score
    def print_score(self):
        print(&#39;%s:%s&#39;%(self.name,self.score))

bart = Student(&#39;Boyuan Zhou&#39;,100)
lisa = Student(&#39;Maomao&#39;,100)
bart.name= &#39;jeff&#39;
print(bart.name)
jeff

Because classes can serve as templates Therefore, when creating an instance, we can force-fill in some attributes that we think must be bound. By defining a special __init__ method, when creating an instance, the name, score and other attributes are tied to it:

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

Note that the first parameter of the __init__ method is always self, which means The created instance itself, therefore, within the __init__ method, you can bind various properties to self, because self points to the created instance itself.

With the __init__ method, when creating an instance, you cannot pass in empty parameters. You must pass in parameters that match the __init__ method, but self does not need to be passed. The Python interpreter itself The instance variable will be passed in:

class Student(object):
    def __init__(self,name,score):
        self.name = name
        self.score = score
    def print_score(self):
        print(&#39;%s:%s&#39;%(self.name,self.score))

bart = Student(&#39;Boyuan Zhou&#39;,100)
lisa = Student(&#39;Maomao&#39;,100)
bart.name= &#39;jeff&#39;
print(bart.name)
print(bart.score)
jeff
100

Compared with ordinary functions, the function defined in the class has only one difference, that is, the first parameter is always the instance variable self, and when calling, there is no need to pass the parameter. Other than that, class methods are no different from ordinary functions, so 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. In the Student class above, each instance has its own name and score data. We can access this data through functions, such as printing a student's score

>>> std1 = {&#39;name&#39;:&#39;jeff&#39;,&#39;score&#39;:100}
>>> std2 = {&#39;name&#39;:&#39;xin&#39;,&#39;score&#39;:0}
>>> def print_score(std):
...     print(&#39;%s:%s&#39;%(std[&#39;name&#39;],std[&#39;score&#39;]))
...
>>> print_score(std1)
jeff:100
>>> print_score(std2)
xin:0

However, since the Student instance itself owns this data, to access this data, there is no need to access it from external functions. You can directly Define the function to access data inside the Student class, thus encapsulating the "data". These functions that encapsulate data are associated with the Student class itself. We call them methods of the class:

class Student(object):
    def __init__(self,name,score):
        self.name = name
        self.score = score
    def print_score(self):
        print(&#39;%s:%s&#39;%(self.name,self.score))

To define a method, except that the first parameter is self, the others are the same as ordinary functions. To call a method, you only need to call it directly on the instance variable. Except for self, you do not need to pass it. Other parameters are passed in normally:

bart.print_score()
jeff:100

In this way, when we look at the Student class from the outside, we only need to know how to create an instance. The name and score need to be given, and how to print is defined internally by the Student class. These data and logic are "encapsulated" and are easy to call, but there is no need to know the details of the internal implementation.

Another benefit of encapsulation is that you can add new methods to the Student class, such as get_grade:

class Student(object):
    def __init__(self,name,score):
        self.name = name
        self.score = score
    def print_score(self):
        print(&#39;%s:%s&#39;%(self.name,self.score))
    def get_grade(self):
        if self.score >=90:
            return 'A'
        elif self.score>=600:
            return  'B'
        else:
            return  'C'
bart = Student('Boyuan Zhou',100)
lisa = Student('Maomao',100)
bart.name= 'jeff'
bart.print_score()

print(bart.get_grade())
jeff:100
A

Related recommendations:

About python object-oriented sample code


The above is the detailed content of Python object-oriented classes and examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP Strategy PatternNext article:PHP Strategy Pattern