[Quick Review of Python Language] - Functions & Modules & Classes and Objects

Table of contents

introduce

1. Function

1. Function overview

2. Parameters and return values

3. Function call

2. Module

1. Module overview

2. Module application examples

3. Classes and Objects

1. Overview of object-oriented

2. Class

3. Characteristics of classes


introduce

In order to make the code implemented by the program simpler. The program needs to be divided into smaller and smaller components, 3 ways - functions, objects, modules.


1. Function

1. Function overview

C language braces {} are the function body, and Python indented blocks are the function body (with def and colon:)
Variables defined outside the function are global variables ( Uppercase with underscore)
Local variables defined inside the function (lowercase with underscore) are only valid internally

def foodprice(per_price,number):
    sum_price = per_price*number
    return sum_price
PER_PRICE = float(input('请输入单价:'))
NUMBER = float(input('请输入数量:'))
SUM_PRICE = foodprice(PER_PRICE,NUMBER)
print('一共',SUM_PRICE,'元')

==========运行结果==========
请输入单价:15
请输入数量:4
一共 60.0 元

If you want to modify a global variable inside a function and make it effective throughout the program, use the keyword global:

def foodprice(per_price,number):
    global PER_PRICE
    PER_PRICE = 10
    sum_price = per_price*number
    return sum_price

2. Parameters and return values

In python, function parameters are divided into three types: positional parameters, variable parameters, and keyword parameters. The types of parameters are different, and the methods of passing parameters are also different.

①Positional parameters
Positional parameters: The incoming parameter values ​​are assigned to the parameters in order of position.
Transmission method: Just pass in the parameters directly. If there are multiple parameters, the order of position cannot be changed. If the order is exchanged, the function results will be different

def sub(x,y):
    return x-y
>>> sub(10,5)
5
>>> sub(5,10)
-5

②Keyword parameters
Keyword parameters: Specify the parameters that need to be assigned by parameter name, and the parameter order can be ignored
Transmission method: 2, One is to directly pass in the parameters, and the other is to encapsulate the parameters into a dictionary first, and then add two asterisks in front of the encapsulated dictionary ** pass in

>>> sub(y=5,x=10)
5
>>> sub(**{'y':5,'x':10})
5

③Default value parameter
When a function call forgets to give a parameter value, the default value will be used instead (to prevent an error)

def sub(x=100,y=50):
    return x-y
>>> sub()
50
>>> sub(51)
1
>>> sub(10,5)
5

④Variable parameters
Variable parameters: When defining function parameters, we don’t know how many parameters are needed, just add an asterisk * in front of the parameters.

def var(*param):
    print('可变参数param中第3个参数是:',param[2])
    print('可变参数param的长度是:',len(param))
>>> var('BUCT',1958,'Liming',100,'A')
可变参数param中第3个参数是: Liming
可变参数param的长度是: 5

In addition to variable parameters, there can also be ordinary parameters (general parameters need to use keyword parameters to pass values):

def var(*param,str1):
    print('可变参数param中第3个参数是:',param[2])
    print('可变参数param的长度是:',len(param))
    print('我是普通参数:',str1)
>>> var('BUCT',1958,'Liming',100,'A',str1 = '普参')
可变参数param中第3个参数是: Liming
可变参数param的长度是: 5
我是普通参数: 普参

⑤The return value of the function
If the return value is not specified with return, an empty None will be returned

result = var('BUCT',1958,'Liming',100,'A',str1 = '普参')
>>> print(result)
None

If the function is changed to:

def var(*param,str1):
    print('可变参数param中第3个参数是:',param[2])
    print('可变参数param的长度是:',len(param))
    print('我是普通参数:',str1)
    return param
>>> print(result)
('BUCT', 1958, 'Liming', 100, 'A')


3. Function call

Custom function: define first and then call
Built-in function: call directly, some are in specific modules, you need to import the corresponding module first

①Nested call
Inline function/inner function: Define another function inside the function, and its scope is only within the indented block of its adjacent outer function.

②Use closures
Closure: an important grammatical structure in functional programming, referencing variables in the external scope (not the global scope) in an internal function . At this time, this internal function is called a closure function. The following sub2(b) refers to a, which is a closure function:

def sub(a):
    def sub2(b):
        result = a-b
        return result
    return sub2
print(sub(10)(5))
运行结果:5

Note: The essence of a closure is still an embedded function and cannot be accessed in the global scope. The local variables of the external function sub are global variables for the closure and can be accessed but cannot be modified.

③Recursive call
Recursion: Strictly speaking, it belongs to the category of algorithms and does not belong to the scope of grammar. The act of a function calling itself is called recursion.
Two conditions: calling the function itself and setting the correct return conditions. For example, calculate the factorial of a positive integer N: 

Conventional iterative algorithm:

def factorial(n):
    result = n
    for i in range(1,n):
        result *= i
    return result
print(factorial(10))
运行结果:3628800

Iterative Algorithms:

def factorial(n):
    if n == 1:
        return 1
    else:
        return n*factorial(n-1)
print(factorial(10))
运行结果:3628800

Note: Python's defaultrecursion depth is 100 levels (limited). You can also use sys.setrecursionlimit(x) to specify the recursion depth. Recursion is dangerous (consuming time and space) because it is based on stack popping and popping operations; when recursion forgets to return/when the correct return conditions are not set, it will cause the program to crash and consume all memory.


2. Module

1. Module overview

A module is actually a more advanced package. The previous container (tuple, list) is the encapsulation of data, the function is the encapsulation of statements, the class is the encapsulation of methods and attributes, and the module is the encapsulation of the program. ——It is the .py file we saved to implement specific functions

namespace: a dictionary containing one or more variable names and their corresponding object values. Python can call variables in the local namespace and global namespace.
If a local variable has the same name as a global variable, the global variable will be blocked when the local variable is called inside the function.
If you want to modify the value of the global variable within the function, you need to use global

①Module import method
Method 1:

import modulename
import modulename1,modulename2

When using a function, modulename.functionname() can be used

Method Two:

from  modulename  import functionname1,functionname2

Method three:

import modulename as newname

It is equivalent to giving the module a new name, which is easier to remember and call.

② Custom modules and packages

Custom module:
The mine.py file written is placed in the same directory as the calling program. You can import mine when using it in other files.

Customized package:
In large-scale project development, in order to avoid duplication of module names, Python has introduced a method of organizing modules by directory, called a package.
A package is a hierarchical file directory structure that defines a namespace consisting of modules, sub-packages, sub-packages under sub-packages, etc.
As long as the top-level registration does not have the same name as others, all internal modules will not conflict. ——P114

③Install third-party packages
pip install xxxx

2. Module application examples

①Date and time related: datatime module
Import:

from datetime import datetime
#不能import datetime,可以import datetime.datetime(因为datetime模块里还有一个datetime类)

Get the current date and time:

>>> now = datetime.now()
>>> print(now)
2023-10-05 17:28:24.303285

Get the specified date and time:

>>> dt = datetime(2020,12,12,11,30,45)
>>> print(dt)
2020-12-12 11:30:45

Convert datetime and timestamp to each other:
Take the time of 1970-1-1 00:00:00 UTC+00:00 as the epoch time, record it as 0, and the current time is relative The number of seconds in epoch time is called timestamp.
The current time stored in the computer is expressed in timestamp, regardless of the time zone. The timestamp of computers around the world is the same at any time.

>>> dt = dt.timestamp()
>>> print(dt)
1607743845.0
#再转换回去:
>>> dt = datetime.fromtimestamp(dt)
>>> print(dt)
2020-12-12 11:30:45

Convert str to datetime:
The date and time type input by the user is a string. To process the date and time, str must be converted to datetime

>>> test = datetime.strptime('2023-10-05  17:49:00','%Y-%m-%d %H:%M:%S')  #特殊字符规定了格式
>>> print(test)
2023-10-05 17:49:00

Convert datetime to str:
If there is a datetime object, it must be formatted into characters before it can be displayed to the user

>>> now = datetime.now()
>>> print(now.strftime('%a,%b %d %H:%M'))
Thu,Oct 05 17:28

datetime addition and subtraction calculation: (then import the timedelta class)

>>> from datetime import datetime,timedelta
>>> now = datetime.now()
>>> now
datetime.datetime(2023, 10, 5, 17, 58, 9, 377124)
>>> now + timedelta(hours = 2)
datetime.datetime(2023, 10, 5, 19, 58, 9, 377124)
>>> now - timedelta(days = 3)
datetime.datetime(2023, 10, 2, 17, 58, 9, 377124)

Convert local time to UTC time: (then import the timedelta and timezone classes)
The local time is the time in the system's set time zone, such as Beijing The time is the time in the UTC+8:00 time zone, and the UTC time refers to the time in the UTC+0:00 time zone. There is a time zone attribute tzinfo in datetime.

>>> from datetime import datetime,timedelta,timezone
>>> new_utc = timezone(timedelta(hours = 8)) #创建新时区UTC+8:00
>>> new_utc1 = timezone(timedelta(hours = 7)) #创建新时区UTC+7:00
>>> now = datetime.now()
>>> now
datetime.datetime(2023, 10, 5, 18, 9, 17, 667655)
>>> test = now.replace(tzinfo = new_utc) #为当前时间强制设置新的时区
>>> test
datetime.datetime(2023, 10, 5, 18, 9, 17, 667655, tzinfo=datetime.timezone(datetime.timedelta(0, 28800)))
>>> test1 = now.replace(tzinfo = new_utc1) #为当前时间强制设置新的时区UTC+7:00
>>> test1
datetime.datetime(2023, 10, 5, 18, 9, 17, 667655, tzinfo=datetime.timezone(datetime.timedelta(0, 25200)))

Time zone conversion:
First use the utcnow() method provided by the datetime class to obtain the current UTC time, and then use the astimezone() method to convert to the time in any time zone

②Read and write JSON data: json module
JSON is a lightweight data exchange format, which is equivalent to the dictionary format in Python, and can contain square brackets. Array (list). The json module specializes in solving json format data and provides 4 methods: dumps(), dump(), loads(), load()
dumps(), dump() to implement the serialization function:

dumps() implements serializing data into a string str. When using dump(), you must pass a file descriptor and save the serialized string str to a file.

>>> import json
>>> json.dumps('huang')
'"huang"'
>>> json.dumps(13.14)
'13.14'
>>> dict1 = {'name':'huang','school':'buct'}
>>> json.dumps(dict1)
'{"name": "huang", "school": "buct"}'

>>> with open("D:\\json_test.json","w",encoding = 'utf-8')as file_test:
    json.dump(dict1,file_test,indent = 4)
运行结果:dump()方法将字典数据dict_test保存到D盘文件夹下的json_test.json文件中,里面的内容如下
{
    "name": "huang",
    "school": "buct"
}

loads(), load() are deserialization methods:

loads() only completes the deserialization, load() only receives the file descriptor and completes reading the file and deserialization.

>>> json.loads(json.dumps(dict1))  #loads直接操作程序中的字典
{'name': 'huang', 'school': 'buct'}   #dumps将字典序列化成str,loads又使其恢复字典身份

>>> with open("D:\\json_test.json","r",encoding = 'utf-8')as file_test:  #读刚才保存的序列化str字符串数据
    test_loads = json.loads(file_test.read())  #用loads实现反序列化
    file_test.seek(0) #重新定位在文件的第0位及开始位置
    test_load = json.load(file_test)  #用load实现反序列化
>>> print(test_loads)
{'name': 'huang', 'school': 'buct'}
>>> print(test_load)
{'name': 'huang', 'school': 'buct'}

③System-related: sys module
sys is a built-in module of python, which contains system-related information. You can view the available methods (many) of the sys module through help(sys) or dir(sys). Here are a few.
sys.path contains a list of directory names for input modules:

>>> sys.path
['',
 'D:\\python3.6.6\\Lib\\idlelib', 
'D:\\python3.6.6\\python36.zip', 
'D:\\python3.6.6\\DLLs', 
'D:\\python3.6.6\\lib', 
'D:\\python3.6.6', 
'D:\\python3.6.6\\lib\\site-packages']

This command obtains the string collection of the specified module search path. Place the written module under a path obtained above, and you can find it correctly when using import. You can also use sys.path.append (custom path) to add the module path. ——"The program cannot be found if the custom module is placed randomly!"
sys.argv passes parameters from the outside to the inside of the program:
????< /span>
The sys.argv variable is a string list containing command line parameters. Use the command line to pass parameters to the program. The name of the script is the first parameter in the sys.argv list.

④Mathematics: math module
The math module is also a built-in module of python, which contains information related to mathematical operation formulas——P125

⑤Random number: random module
List common modules:
Generate random integers (upper and lower limits need to be specified , and the lower limit is smaller than the upper limit):randint

import random
>>> random.randint(10,2390)  #生成指定范围内的随机整数
2375

Generate a random floating point number: random

>>> random.random()
0.9935870033845187
>>> random.uniform(10,100)
27.07308173076904
>>> random.uniform(100,10)
18.198994262912336

Random characters: choice

>>> random.choice('98%$333#@')
'3'

Shuffle:shuffle

>>> test = ['a','B',1,2,5,'%']
>>> random.shuffle(test)
>>> print(test)
[5, 1, 2, 'a', 'B', '%']

3. Classes and Objects

1. Overview of object-oriented

Object Oriented Programming (OOP) is a programming idea, an abstract thinking process and object-oriented method reflected in the establishment of models.
A model is used to reflect the characteristics of things in the real world. It is an abstraction of the characteristics and change patterns of things, and it is a more general, more concentrated, and more profound description of the characteristics of the object.
OOP regards objects as the basic unit of the program. An object contains data and functions for operating data.

Introduction to terminology:

1、类:是创建对象的代码段,描述了对象的特征、属性、要实现的功能,以及采用的方法等。
2、属性:描述了对象的静态特征。
3、方法:描述了对象的动态动作。
4、对象:对象是类的一个实例,就是模拟真实事件,把数据和代码段都集合到一起,即属性、方法的集合。
5、实例:就是类的实体。
6、实例化:创建类的一个实例过程。
7、封装:把对象的属性、方法、事件集中到一个统一的类中,并对调用者屏蔽其中的细节。
8、继承:一个类共享另一个类的数据结构和方法的机制称为继承。起始类称为基类、超类、父类,而继承类称为派生类、子类。继承类是对被继承类的拓展。
9、多态:一个同样的函数对于不同的对象可以具有不同的实现。
10、接口:定义了方法、属性的结构,为其成员提供违约,不提供实现。不能直接从接口创建对象,必须首先创建一个类来实现接口所定义的内容。
11、重载:一个方法可以具有许多不同的接口,但方法的名称是相同的。
12、事件:事件是由某个外部行为所引发的对象方法。
13、重写:在派生类中,对基类某个方法的程序代码及进行重新编码,使其实现不同的功能。
14、构造函数:是创建对象所调用的特殊方法。
15、析构函数:是释放对象时所调用的特殊方法。

2. Class

①Definition of class
A class is the splicing of attributes and methods of an object. Static features are called attributes, and dynamic actions are called methods.

>>> class Person:  #规定类名以大写字母开头
    #属性
    skincolor = "yellow"
    high = 185
    weight = 75
    #方法
    def goroad(self):
        print("人走路动作的测试...")
    def sleep(self):
        print("睡觉,晚安!")

②Use of classes (classes are instantiated into objects)

>>> p = Person()  #将类实例化为对象,注意后面要加括号()

③Class construction method and proprietary method
Class construction method: __int__(self). As long as an object is instantiated, this method will be automatically called when the object is created - parameters can be passed in when instantiating the object, and these parameters will be automatically passed into the __int__(self, param1, param2...) method , you can customize the initialization operation of the object by overriding this method.

>>> class Bear:
    def __init__(self,name):
        self.name = name
    def kill(self):
        print("%s是保护动物不可猎杀"%self.name)

        
>>> a = Bear("狗熊")
>>> a.kill()
狗熊是保护动物不可猎杀

Explanation: Compared with Person(), the __init__() method is rewritten here, otherwise the default is __init__(self). A parameter name is given in Bear(), which becomes __init__(self, name). The first parameter self is the default, so "bear" is passed to name when calling. You can also give name default parameters, so that even if you forget to pass in parameters, the program will not report an error:

>>> class Bear:
    def __init__(self,name = "狗熊"):
        self.name = name
    def kill(self):
        print("%s是保护动物不可猎杀"%self.name)
    
>>> b = Bear()
>>> b.kill()
狗熊是保护动物不可猎杀
>>> c = Bear("丹顶鹤")
>>> c.kill()
丹顶鹤是保护动物不可猎杀

④Class access rights
In C++ and JAVA, the keywords public and private are used to indicate whether the access rights are public or private. In Python, the properties and methods of objects are public and public by default, and can be accessed through the dot (.) operator. For example, when accessing the kill() function (method) above, you can also access variables:

>>> class Test:
    name = "大连橡塑"

    
>>> a = Test()
>>> a.name
'大连橡塑'

If a variable is preceded by a double underscore (__), it means that it is declared as a private variable and cannot be accessed:

>>> class Test:
    __name = "君欣旅店"
    
>>> a = Test()
>>> a.__name
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    a.__name
AttributeError: 'Test' object has no attribute '__name'

Private variables can be accessed using function methods:

>>> class Test:
    __name = "君欣旅店"
    def getname(self):
        return self.__name

>>> a = Test()
>>> a.getname()
'君欣旅店'

Private variables can also be accessed through the "_class name__ variable name" format:

>>> a._Test__name
'君欣旅店'

(It can be seen that python’s private mechanism is pseudo-private, python classes have no permission control, and variables can be called by the outside world)

⑤Get object information
After the class instantiates the object (such as a = Test()), the object can call the attributes and methods of the class:
That is a.getname(), a.name, a.kill() these

3. Characteristics of classes

①Encapsulation
Formally, objects encapsulate attributes, which are variables, while methods and functions are highly independent modules. Encapsulation is an information masking technology that makes the data more Safety!
If a list is essentially a sequence object in python, sort() is one of the methods/functions:

>>> list1 = ['E','C','B','A','D']
>>> list1.sort()
>>> list1
['A', 'B', 'C', 'D', 'E']

②Polymorphism
Different objects respond to different actions for the same method, which is polymorphism (the internal method/function names are the same, but the functions defined in different classes are different):

>>> class Test1:
    def func(self):
        print("这是响应1...")        
>>> class Test2:
    def func(self):
        print("这是响应2...")    
>>> x = Test1()
>>> y = Test2()
>>> x.func()
这是响应1...
>>> y.func()
这是响应2...

Note: self is equivalent to the this pointer in C++. Countless objects can be generated from the same class. These objects all originate from the properties and methods of the same class. When a method of an object is called, the object will pass itself as the first parameter to the self parameter. When receiving the self parameter , python will know which object is calling the method.

③Inheritance
Inheritance is a mechanism for subclasses to automatically share parent class data and methods. The syntax format is as follows:

class ClassName(BaseClassName):
...
ClassName:子类名称,第一个字母必须大写。
BaseClassName/paraname:父类名称。

Subclasses can inherit any attributes and methods of the parent class. The class Test_list is defined as follows to inherit the attributes and methods (append and sort) of the list:

>>> class Test_list(list):
    pass

>>> list1 = Test_list()
>>> list1.append('B')
>>> list1
['B']
>>> list1.append('UCT')
>>> list1
['B', 'UCT']
>>> list1.sort()
>>> list1
['B', 'UCT']

Notes when using the class inheritance mechanism:
a. If a method or attribute with the same name as the parent class is defined in the subclass, the corresponding attribute or method in the parent class will be automatically overwritten.
b. The subclass overrides the attribute or method of the same name in the parent class. If the overridden method of the subclass with the same name does not introduce the method of the parent class with the same name, the instantiated object calls the parent class's method. Methods with the same name will cause an error:

import random
class Dog:
    def __init__(self):
            self.x = random.randint(1,100)  #两个缩进
            self.y = random.randint(1,100)
    def run_Dog(self):
            self.x += 1
            print("狗狗的位置是:",self.x,self.y)

        
class Dog1(Dog):
    pass

class Dog2(Dog):
    def __init__(self):
            self.hungry = True  
    def eat(self):
            if self.hungry:
                print("狗想吃东西了!")
                self.hungry = False
            else:
                print("狗吃饱了!")

调用:
>>> dog = Dog()
>>> dog.run_Dog()
狗狗的位置是: 62 69
>>> dog1 = Dog1()
>>> dog1.run_Dog()
狗狗的位置是: 29 89
>>> dog2 = Dog2()
>>> dog2.eat()
狗想吃东西了!
>>> dog2.eat()
狗吃饱了!
>>> dog2.run_Dog()  #报错报错!!!

Analysis: The subclass Dog2 rewrites the constructor __init__(self) of the parent class (base class) Dog, so the methods in the parent class constructor are overwritten. To solve this problem, we need towhen rewriting the method of the parent class with the same name in the subclass, first introduce the method of the parent class with the same name. Two techniques:a , call unbound parent class method;b. Use super function

a. Call unbound parent class method——Syntax format: paraname.func(self). Parent class name.Method name.(self)
Changes to the Dog2 class in the above example code:

def __init__(self):
        Dog.__init__(self)   #加了这一行
            self.hungry = True  
调用:
>>> dog2 = Dog2()
>>> dog2.run_Dog()
狗狗的位置是: 85 16

b. Use the super function. This function can automatically find the parent class method and the passed self parameter. The syntax format is: super().func([parameter]). parameter is an optional parameter and can be omitted if it is self.
Dog2 class changes to the above example code:

def __init__(self):
            super().__init__()  #加了这一行
            self.hungry = True

调用:
>>> dog2 = Dog2()
>>> dog2.run_Dog()
狗狗的位置是: 96 82

The convenience of using the super function is that you don’t need to write any name about the base class (parent class), just write the overridden method directly, and it will automatically go to the parent class to find it, especially in multiple inheritance, or if there are multiple subclasses When it comes to ancestor classes, it can automatically skip multiple levels to find them. If you want to change the parent class in the future, just modify the parent class name in the brackets () without modifying the contents of the overridden method of the same name.

④Multiple inheritance
A subclass inherits the attributes and methods of multiple parent classes at the same time:

class Classname(Base1,Base2,Base3):
    ...

Although the mechanism of multiple inheritance allows subclasses to inherit multiple properties and methods, it can easily lead to code confusion and unforeseen bugs. Generally, try to avoid using it.

Guess you like

Origin blog.csdn.net/weixin_51658186/article/details/133977860