三、函数、类和对象

# 三、函数、类和对象

# 3.1 函数

# 3.1.1 定义

def add(num1,num2):
    return num1+num2

res = add(1,2)
print(res)
1
2
3
4
5
3

# 3.1.2 参数

顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。

  • 默认参数
# 默认参数
def fn(x,y=1):
    return x*y
1
2
3
  • 可变参数
def calc(*nums):
    print(nums)
    sum = 0
    for num in nums:
        sum += num
    return sum

sum = calc(1,2,3,4,5)

print(sum)
1
2
3
4
5
6
7
8
9
10
(1, 2, 3, 4, 5)
15
  • 关键字参数
def getName(**obj):
    if 'name' in obj:
        return obj['name']
    else:
        return 'None'

obj = {'name':'Adam'}
myName = getName(**obj)
print(myName)
1
2
3
4
5
6
7
8
9
Adam

# 3.1.3 注意事项

  1. 在函数内部的任何位置定义的变量,在函数体的其他部分都可以被访问和使用,只要该变量在使用之前已经被定义。
import math
def getFlag(num):
    if num > 10:
        flag = 1
    else:
        flag = 0
    flag = bool(flag)
    return flag

res = getFlag(1)
print(res)
1
2
3
4
5
6
7
8
9
10
11
False

# 3.1.4 空函数

def fn():
    pass
1
2

# 3.2 高阶函数

# 3.2.1 filter

# filter
def fn(num):
    return num > 10

res = filter(fn, [1, 5, 100, 23, 5, 15])

for value in res:
    print(value)

print(list(res))
1
2
3
4
5
6
7
8
9
10
100
23
15



---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

Cell In[48], line 10
      7 for value in res:
      8     print(value)
---> 10 print(list(res))


TypeError: 'dict_items' object is not callable

# 3.2.2 map

myData = map(lambda x: x * x, [1, 2, 3, 4, 5])
print(list(myData))
1
2

# 3.2.3 reduce

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

from functools import reduce
def fn(x, y):
    return x + y + 10

res = reduce(fn, [1, 2, 3, 4, 5, 6])
print(res)
1
2
3
4
5
6

# 3.2.4 返回函数

def getSum(*args):

    def calc():
        sum = 0
        for num in args:
            sum += num
        return sum

    return calc


sum = getSum(1, 2, 3, 4, 5)
print(sum())
1
2
3
4
5
6
7
8
9
10
11
12
13

# 3.2.5 lambda 函数

data = [1,2,3,4,5]
newData = map(lambda x:x*x, data)
print(list(newData))
1
2
3

# 3.3 类

# 3.3.1 定义

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def getName(self):
        return self.name


XM = Person('Adam',18)
name = XM.getName()
print(name)
1
2
3
4
5
6
7
8
9
10
11
12

# 3.3.2 继承

# 单继承

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def getName(self):
        return self.name

    def setName(self, name):
        self.name = name

class Stu(Person):

    def __init__(self, name, age, ID):
        # Person.__init__(self, name, age)
        super().__init__(name, age)
        self.ID = ID

    def getInfo(self):
        print(f'name:{self.name}, age:{self.age}, ID:{self.ID}')

stu = Stu('Adam',18,'510802')
stu.getInfo()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 多重继承

(1)基础版

class Person:
    def __init__(self, name):
        self.name = name

    def getName(self):
        return self.name

    def setName(self, name):
        self.name = name

class Animal:
    def __init__(self, age):
        self.age = age

    def getAge(self):
        return self.age

class Stu(Person, Animal):

    def __init__(self,name,age,ID):
        Person.__init__(self, name)
        Animal.__init__(self, age)
        self.ID = ID

    def getInfo(self):
        print(f'name:{self.name}, age:{self.age}, ID:{self.ID}')

stu = Stu('Adam',18,'510802')
stu.getInfo()
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

(2)super 版

class Person:
    def __init__(self, name, **kwargs):
        self.name = name
        super().__init__(**kwargs)

    def getName(self):
        return self.name

    def setName(self, name):
        self.name = name

class Animal:
    def __init__(self, age, **kwargs):
        self.age = age
        super().__init__(**kwargs)

    def getAge(self):
        return self.age

class Stu(Person, Animal):

    def __init__(self,name,age,ID,**kwargs):
        # Person.__init__(self, name)
        # Animal.__init__(self, age)
        super().__init__(name=name,age=age,**kwargs)
        self.ID = ID

    def getInfo(self):
        print(f'name:{self.name}, age:{self.age}, ID:{self.ID}')

    # 重写
    def getName(self):
        print(f'Stu\'s name:{self.name}')

stu = Stu('Adam',18,'510802')
stu.getInfo()
stu.getName()
# print(stu.mro())
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
33
34
35
36
37
38

# 多级继承

class Person:
    def __init__(self,age,**kwargs):
        super().__init__(**kwargs)
        self.age = age

class Man(Person):
    def __init__(self,name,**kwargs):
        super().__init__(**kwargs)
        self.name = name

    def getName(self):
        return self.name


class Stu(Man):
    def __init__(self,ID,**kwargs):
        super().__init__(**kwargs)
        self.ID = ID

    def getInfo(self):
        name = super().getName()
        print(f'name:{name}, age:{self.age}, ID:{self.ID}')

info = {'ID':"510802", "name":'Adam', "age":18}
XM = Stu(**info)
XM.getInfo()
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

# 多态

调用方只管调用,不管细节

def run(water):
    water.show()

class Water:
    def show(self):
        pass

class Ice(Water):
    def show(self):
        print('Im ice')

class Steam(Water):
    def show(self):
        print('Im water')

run(Ice())
run(Water())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 3.3.3 类、静态方法

class Person:

    @classmethod
    def getClassName(cls):
        print('Person')

    @staticmethod
    def getInfo():
        print('Class Person')

Person.getInfo()
1
2
3
4
5
6
7
8
9
10
11

区别:

  • 类方法需要自身类 clc