Summary of relevant knowledge such as introduction to Python

Time:2022-1-2
catalogue
  • preface
  • 1、 Class definition and use
  • 2、 Class method
  • 3、 Properties of class
  • 4、 Special methods commonly used in classes

preface

Python is object oriented programming.

A basic principle of object-oriented programming is:

A computer program is composed of a plurality of units or objects that can act as subroutines.

A key concept of object-oriented programming is:

Data and data operations (i.e. function methods) are encapsulated together.

This concept is already familiar to me who are exposed to C + +. Is the “class” class.
Python fully supports all basic object-oriented functions, such as:

Encapsulation, inheritance, polymorphism, and override or override of base class methods.

Please let me walk slowly.

1、 Class definition and use

In C + +, classes are derivatives of “structures”. In Python, classes appear as a completely independent concept.

1. Definition of class:

?
1
2
class ClassName:
    ......

2. Initialization function and self parameter: [very important!!!]

?
1
2
3
4
def __init__(self,a,b,......):
    self. variables1=a
    self. variables2=b
    ......

① Python defines “variables” in initialization functions.
When we want to use this class, we can directly assign values to the variables in the initialization function.
Of course, you can assign values to variables directly without writing formal parameters a, B, etc.
② The self parameter represents this class.
When you write a function (that is, a method) in a class, you must pass in the self parameter. Examples will be given later.

[from this, we can find that the init initialization function in Python is the same as the constructor in C + +, and its principle is actually the same]

3. Use class for external variables: that is, call the initial function of the class

?
1
2
3
4
5
6
7
8
class A:
    def __init__(self,p,q):
        self.a=p
        self.b=q
        
example=A(1,2#Call the initialization function and pass in the formal parameters p = 1 and q = 2. At this time, it indicates that example uses class A
print(A.a)      #Output 1
print(A.b)      #Output 2

4. Scope of application of restricted variables: private or public

As we know, there are three kinds of variables in C + + classes: public, protected and private. Of course there are in Python, but the writing method is different.
In particular, the calling methods of private variables “in class” and “out of class” are different.
There are two methods to obtain the value of private variable outside the class:

① Through a specific “interface”: that is, call functions and methods in the class, and use private variables in the class through self
② Through a special method: example_ Classname (class name)__ Var (variable)

If you call private directly without thinking, the program will have an attributeerror error error. Of course, you can’t directly operate on the value and assignment of private variables.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
class A:
    def __init__(self,a,b,c):
        self.one=a      #No modification, equivalent to public
        self._two=b     #Add an underscore, which is equivalent to protected
        self.__three=#Add two underscores, which is equivalent to private
    def get_all(self):
        print(self.one)     #Calling method in class: the format is the same as the definition
        print(self._two)
        print(self.__three)
        
example=A(1,2,3)
example.get_all()         #Get private value through interface
print(example._A__three)  #Get the private value through a special method

The above is the basic knowledge. We deepen our impression through an example program:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Human:
    def __init__(self,name,height,weight,sex):
        self.name=name
        self._height=height
        self.__weight=weight
        self.sex=sex
    def get_info(self):
        print(self.name)
        print(self._height)   #Call the protected variable inside the class with an underscore
        print(self.__weight)  #Call the private variable inside the class with two underscores
        print(self.sex)
    def get_weight(self):   #Interface: obtain the value of private variable through method, which is equivalent to a channel
        print("His(Her) weight is:")
        print(self.__weight)
 
DIONA=Human("diona",'150cm','50kg','female(♀)')
#The variables of private and protected attributes can be used normally by accessing and outputting variables through the internal functions of the class.
DIONA.get_info()
 
#Height is the protected attribute. When calling outside the class, an underscore should be added
print(DIONA._height)
#Weight is a private attribute. When calling outside the class, a special method should be used: XXX_ Classname (class name)__ Varname (variable name)
print(DIONA._Human__weight)
 
#Use the interface to get the value of weight
DIONA.get_weight() 

2、 Class method

Class methods are divided into “common methods”, “private methods”, “static methods” and “class methods”. This article describes the latter two in detail.

1. Static method:
Also known as “non instance method”, it is generally an instance independent method, which is used for incidental calls of other methods. It is better to annotate with @ staticmethod before use

2. Class method:
Methods that accept class properties. At least one formal parameter CLS must be accepted, but no value needs to be passed for CLS when calling. It is best to annotate with @ classmethod.
p. S: what is “class attribute”? Variables that are not written in the init function but are written directly in the class.

?
1
2
3
4
class A:
    one=0  #This one is a "class attribute"
    def __init__(self):
        self.two=0   #This two is the "self attribute"

3. Example method:
This is the general way to use the self attribute. The methods described in “one” above are all instance methods.

4. External call rules:
① Instance method: only instance name can be used.
② Static methods and class methods: you can use either the instance name or the class name.

Program instance:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Student:
    _number=0    #This number is a class attribute, which is directly defined in the class and must be called by class methods
    def __init__(self,name,uid):
        self._name=name
        self._uid=uid
        Student._number+=1     #For each initialization, the number of students is increased by 1
        #In addition, when calling class properties, use the class name: classname varname
        
    #Instance method: operate on variables defined by self
    def get_name(self):
        print(self._name)
    
    #Static methods: (non instance methods) generally instance independent methods, which are used for incidental calls of other methods.
    @ staticmethod
    def pls(a,b):
        return a+b;
    
    @ classmethod
    #Class method: at least one formal parameter CLS must be accepted, but no value needs to be passed for CLS when calling
    def get_number(cls):  
        print(cls._number)
 
lwc=Student('lwc','20009100132')
gtj=Student('gtj','20009100128')
wxm=Student('wxm','20018900232')
 
#The instance method is called externally, and the instance name is used. Instance methods cannot be called with a class name.
lwc.get_name()
 
#Call class methods externally, using class name or instance name.
Student.get_number()
lwc.get_number()

3、 Properties of class

Generally speaking, class attributes are “variables stored in a class”. Generally, there are “class attributes” and “self attributes”.
Class attributes have been mentioned in “2”. There is also a content called “dynamically adding attributes” and “dynamically deleting attributes”, which are rarely used in practice. I will talk about it here.

4、 Special methods commonly used in classes

Python classes have a large number of special methods. The initialization function mentioned earlier is “constructor”, which is a special method. Its corresponding “destructor”__ deal __ () is also a special method.
A number of special methods are listed below:

Summary of relevant knowledge such as introduction to Python

This is the end of this article on the summary of relevant knowledge such as the introduction to python. For more relevant Python content, please search the previous articles of developeppaper or continue to browse the relevant articles below. I hope you will support developeppaper in the future!