python气象信息系统工程 第二章

第二章

2.1 变量

1
2
3
4
5
6
#同一个对象也可以被多个变量所指向
n = 1
m = n
print(m is n)
n = 2
print(m)
True
1
1
2
3
4
# 可以将已经赋值过的变量和数值混合使用
a = 10
print(a + 2)
print(a)
12
10
1
2
3
4
5
6
7
8
# 赋值
a = a + 2
print(a)
#等价于
a = 10
temp = a + 2
a = temp
print(a)
12
12

2.2 原生数据类型

2.21 数值

1
2
3
# 运算顺序
print(1 + 2 * 3)
print((1 + 2) * 3)
7
9
1
2
# 浮点数
print(123.0,1.23e2,12300e-2)
123.0 123.0 123.0
1
2
# 复数
print(3.14+15j,314e-2+15j,3.14+1.5e1j)
(3.14+15j) (3.14+15j) (3.14+15j)
1
2
3
# 复数计算
print(1+2j * 2)
print((1+2j) * 2)
(1+4j)
(2+4j)
1
2
3
4
5
# 布尔值
print(True)
print(False)
print(1 > 2)
print(3.14 < 4)
True
False
False
True
1
2
3
4
5
# 布尔值计算
print(True + 1)
print(True + True)
print(True / 2)
print(False + 1)
2
2
0.5
1

2.22 空值

1
2
3
4
5
#空值
print(None)
print(None == 0)
print(None == True)
print(None == False)
None
False
False
False

2.23 字符串

1
2
3
4
5
# 字符串
print('hello')
print("world")
print("hello 'world'")
print('good "morning"')
hello
world
hello 'world'
good "morning"
1
2
3
4
5
6
7
8
9
10
# 多行字符串会保留代码中的换行符和空格
morning = '''Hi!
Good 'morning'
'''
evening = """Hello!
Good "evening"
"""
print(morning)
print(evening)

Hi!
Good 'morning'

Hello!
   Good "evening"
1
2
3
4
5
6
7
# 数值类型互相转化
print(int('32'))
print(float('32'))
# 数值转为字符串
a = str(32.0)
print(a)
print(type(a))
32
32.0
32.0
<class 'str'>
1
2
3
# 转义符
print('hello \n world')
print('hello \'world\'')
hello 
 world
hello 'world'
1
2
3
# 获取字符串长度
print(len('hello'))
print(len('你好'))
5
2
1
2
3
4
# 用in判断是否存在子字符串
poem = 'You need Python'
print('nee' in poem)
print('早' in '早上要吃早餐')
True
True

2.24 列表和元组

1
2
3
4
# 用[]创建列表
list_empty = []
list_str = ['hello', 'good', 'bye']
list_hybrid = [1, 'one', [2, 3], True]
1
2
3
# 用list()将其他序列转为列表
print(list('hello'))
print(list((1,2,3)))
['h', 'e', 'l', 'l', 'o']
[1, 2, 3]
1
2
3
4
# 用索引[index]获取元素
names = ['Liming', 'Lili', 'Daming']
print(names[0])
print(names[1])
Liming
Lili
1
2
3
4
# 通过负向索引从列表中取出对应位置的元素
names = ['Liming', 'Lili', 'Daming']
print(names[-1])
print(names[-3])
Daming
Liming
1
2
3
4
5
# 用索引[index]替换元素
names = ['Liming', 'Lili', 'Daming']
print(names)
names[0] = 'David'
print(names)
['Liming', 'Lili', 'Daming']
['David', 'Lili', 'Daming']
1
2
3
4
5
# 用append()方法添加元素到尾部
names = ['Liming', 'Lili', 'Daming']
print(names)
names.append('David')
print(names)
['Liming', 'Lili', 'Daming']
['Liming', 'Lili', 'Daming', 'David']
1
2
3
4
5
6
7
# 用pop()方法删除元素
names = ['Liming', 'Lili', 'Daming', 'David']
print(names)
names.pop()
print(names)
print(names.pop(0))
print(names)
['Liming', 'Lili', 'Daming', 'David']
['Liming', 'Lili', 'Daming']
Liming
['Lili', 'Daming']
1
2
3
# 用len()函数获取列表长度
names = ['Liming', 'Lili', 'Daming', 'David']
print(len(names))
4
1
2
3
4
5
6
7
8
# 列表的赋值与复制
names = ['Liming', 'Lili', 'Daming', 'David']
visitor = names
print(names)
print(visitor)
names.pop()
print(names)
print(visitor)
['Liming', 'Lili', 'Daming', 'David']
['Liming', 'Lili', 'Daming', 'David']
['Liming', 'Lili', 'Daming']
['Liming', 'Lili', 'Daming']
1
2
3
4
5
6
7
8
# 用copy()方法复制列表
names = ['Liming', 'Lili', 'Daming', 'David']
visitor = names.copy()
print(names)
print(visitor)
names.pop()
print(names)
print(visitor)
['Liming', 'Lili', 'Daming', 'David']
['Liming', 'Lili', 'Daming', 'David']
['Liming', 'Lili', 'Daming']
['Liming', 'Lili', 'Daming', 'David']
1
2
3
4
# 用in判断元素的值是否存在
names = ['Liming', 'Lili', 'Daming', 'David']
print('Lili' in names)
print('Bob' in names)
True
False
1
2
3
4
# 用()创建元组
tuple_empty = ()
tuple_name = ('Lili',)
tuple_score = (10, 2,) # tuple_score = (10, 2)也正确
1
2
3
4
5
# 如果元组只有一个元素,那么元素后面一定要带上逗号,否则赋值给变量的将是元素本身,而不是“装有”单一元素的元组
tuple_wrong = ('wrong')
print(type(tuple_wrong))
tuple_right = ('right',)
print(type(tuple_right))
<class 'str'>
<class 'tuple'>
1
2
3
# 用tuple()将其他序列转换成元组
print(tuple('hello'))
print(tuple([1,2,3]))
('h', 'e', 'l', 'l', 'o')
(1, 2, 3)
1
2
3
# 使用索引[index]获取元素
names = ('Liming', 'Lili', 'Daming')
print(names[0])
Liming
1
2
3
4
# 通过负向索引从元组中取出对应位置的元素
names = ('Liming', 'Lili', 'Daming')
print(names[-1])
print(names[-3])
Daming
Liming
1
2
3
4
5
6
# 元组中元素不可增删和替换,并不代表元素对象不可以变化
tuple_hybrid = (1, 2, [])
print(tuple_hybrid)
print(tuple_hybrid[2])
tuple_hybrid[2].append('hello')
print(tuple_hybrid)
(1, 2, [])
[]
(1, 2, ['hello'])
1
2
3
4
# 用in判断元素的值是否存在
names = ('Liming', 'Lili', 'Daming', 'David')
print('Lili' in names)
print('Bob' in names)
True
False

2.25 集合

1
2
3
4
5
6
7
8
9
# 用{}创建集合
set_empty = set()
set_number = {1, 3, 10, 4, 5, 5}
set_word = {'hello', 'good', 'bye'}
set_hybrid = {'david', 1}
print(set_empty)
print(set_number)
print(set_word)
print(set_hybrid)
set()
{1, 3, 4, 5, 10}
{'good', 'bye', 'hello'}
{1, 'david'}
1
2
3
4
# 用set()将序列转换成集合
print(set('hello'))
print(set(['good', 'bye']))
print(set(('good', 'bye')))
{'h', 'l', 'o', 'e'}
{'good', 'bye'}
{'good', 'bye'}
1
2
# 用in判断元素的值是否存在
print('good' in {'good', 'hello'})
True
1
2
3
4
5
6
7
8
9
10
11
12
13
# 集合运算符
fruit_a = {'apple', 'orange', 'banana'}
fruit_b = {'grape', 'apple', 'cherry'}
fruit_c = {'grape', 'berry', 'cherry'}
print(fruit_a & fruit_b)
print(fruit_a & fruit_c)

fruit_a = {'apple', 'orange', 'banana'}
fruit_b = {'grape', 'apple', 'cherry'}
fruit_c = {'grape', 'berry', 'cherry'}
print(fruit_a | fruit_b)
print(fruit_a | fruit_b | fruit_c)

{'apple'}
set()
{'cherry', 'apple', 'orange', 'grape', 'banana'}
{'cherry', 'apple', 'berry', 'orange', 'grape', 'banana'}

2.2.6 字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 用{}创建字典
dict_empty = {}
dict_hours = {
'hour': 1,
'day': 24,
'week': 168
}
dict_hybrid = {
'clock': 8,
'say': 'good morning',
1: 'room'
}
print(dict_empty)
print(dict_hours)
print(dict_hybrid)
{}
{'hour': 1, 'day': 24, 'week': 168}
{'clock': 8, 'say': 'good morning', 1: 'room'}
1
2
3
4
5
6
7
# 用键[key]获取元素
dict_hours = {
'hour': 1,
'day': 24,
'week': 168
}
print(dict_hours['day'])
24
1
2
3
4
5
# 测试键是否存在
print('month' in dict_hours)
print(dict_hours.get('week'))
print(dict_hours.get('month'))
print(dict_hours.get('month', 'no month'))
False
168
None
no month
1
2
3
4
5
6
7
8
9
# 用键[key]添加或替换元素
dict_ages = {
'Lili': 20,
'Daming': 21
}
print(dict_ages)
dict_ages['Tom'] = 25
print(dict_ages)
dict_ages['Daming'] = 23
{'Lili': 20, 'Daming': 21}
{'Lili': 20, 'Daming': 21, 'Tom': 25}
1
2
3
4
5
6
7
8
# 用keys()方法获取所有键
dict_hours = {
'hour': 1,
'day': 24,
'week': 168
}
print(dict_hours.keys())
print(list(dict_hours.keys()))
dict_keys(['hour', 'day', 'week'])
['hour', 'day', 'week']
1
2
3
4
5
6
7
8
# 用values()方法获取所有值
dict_hours = {
'hour': 1,
'day': 24,
'week': 168
}
print(dict_hours.values())
print(list(dict_hours.values()))
dict_values([1, 24, 168])
[1, 24, 168]
1
2
3
4
5
# 用update()方法更新字典
dict_ages = {'Daming': 21, 'Lili':20}
print(dict_ages)
dict_ages.update({'Daming': 23, 'Tom': 25})
print(dict_ages)
{'Daming': 21, 'Lili': 20}
{'Daming': 23, 'Lili': 20, 'Tom': 25}
1
2
3
4
5
# 用pop()方法删除键值对
dict_ages = {'Daming': 21, 'Lili':20}
print(dict_ages)
print(dict_ages.pop('Lili'))
print(dict_ages)
{'Daming': 21, 'Lili': 20}
20
{'Daming': 21}
1
2
3
4
5
6
7
# 字典的赋值与复制
dict_ages = {'Daming': 21, 'Lili':20}
dict_new = dict_ages
print(dict_new)
dict_ages['Tom'] = 25
print(dict_new)
print(dict_ages)
{'Daming': 21, 'Lili': 20}
{'Daming': 21, 'Lili': 20, 'Tom': 25}
{'Daming': 21, 'Lili': 20, 'Tom': 25}
1
2
3
4
5
6
7
# 使用copy()方法复制一个新的字典对象
dict_ages = {'Daming': 21, 'Lili':20}
dict_new = dict_ages.copy()
print(dict_new)
dict_ages['Tom'] = 25
print(dict_new)
print(dict_ages)
{'Daming': 21, 'Lili': 20}
{'Daming': 21, 'Lili': 20}
{'Daming': 21, 'Lili': 20, 'Tom': 25}

2.3 判断

1
2
3
4
5
# 使用if语句实现条件判断
light_on = True
if light_on:
print('开灯')
print('灯亮了')
开灯
灯亮了
1
2
3
4
5
6
7
# else的使用
light_on = True
if light_on:
print('开灯')
print('灯亮了')
else:
print('灯没开')
开灯
灯亮了

2.3.1 比较操作

1
2
3
4
5
# 逻辑运算符和比较操作符的组合使用
a = 10
print(a > 5 and a < 15)
print(a > 5 and not a < 15)
print(a > 5 or not a < 15)
True
False
True

2.3.2 条件值非布尔值

1
2
3
4
5
6
# if语句的判断条件允许不是布尔值
names = []
if names:
print('有人')
else:
print('没人')
没人

2.3.3 多重条件

1
2
3
4
5
6
7
8
9
clock = 15
if clock < 12:
print('good morning')
elif clock < 18:
print('good afternoon')
elif clock < 21:
print('good evening')
else:
print('good night')
good afternoon

2.4 循环和迭代

2.4.1 循环

1
2
3
4
5
6
# while循环
n = 0
while n < 3:
print(n)
n = n +1
print('循环结束')
0
1
2
循环结束
1
2
3
4
5
6
7
8
9
10
11
12
13
# 用break语句结束循环
names = ['Daming', 'Lili', 'Tom', 'Liming']
i = 0
while True:
if i >= len(names):
print('找不到Tom')
break
elif names[i] == 'Tom':
print('找到Tom了')
break
print(names[i], '不是Tom')
i = i + 1
print('Tom 所对应的索引是', i)
Daming 不是Tom
Lili 不是Tom
找到Tom了
Tom 所对应的索引是 2
1
2
3
4
5
6
7
8
9
10
11
# 用continue语句跳过当前循环
n = 1
n_sum = 0
while n < 10:
if n % 2 == 0:
n = n + 1
continue
print(n, '不是偶数')
n_sum = n_sum + n
n = n + 1
print(n_sum)
1 不是偶数
3 不是偶数
5 不是偶数
7 不是偶数
9 不是偶数
25

2.4.2 迭代

1
2
3
4
5
6
# 在数据长度未知和具体实现结果未知的情况下遍历整个数据结构
fruits = ['apple', 'orange', 'banana']
for fruit in fruits:
print(fruit)
if fruit == 'orange':
print('我最爱orange')
apple
orange
我最爱orange
banana
1
2
3
4
# 字符串迭代
name = 'Tom'
for letter in name:
print(letter)
T
o
m
1
2
3
4
# 对字典的键迭代可以使用keys()方法
dict_ages = {'Daming': 21, 'Lili': 20}
for key in dict_ages.keys():
print(key)
Daming
Lili
1
2
3
4
# 对字典的值迭代可以使用values()方法
dict_ages = {'Daming': 21, 'Lili': 20}
for value in dict_ages.values():
print(value)
21
20
1
2
3
4
# 对字典的键值对迭代可以使用items()方法
dict_ages = {'Daming': 21, 'Lili': 20}
for item in dict_ages.items():
print(item)
('Daming', 21)
('Lili', 20)
1
2
3
4
# 对于元组可以使用单独的变量名将元组“解包”
dict_ages = {'Daming': 21, 'Lili': 20}
for name, age in dict_ages.items():
print(name, 'is', age)
Daming is 21
Lili is 20
1
2
3
4
5
6
# 用break语句结束迭代
fruits = ['apple', 'orange', 'banana']
for fruit in fruits:
if fruit == 'orange':
break
print(fruit)
orange
1
2
3
4
5
6
# 用continue语句跳过当前迭代
fruits = ['apple', 'orange', 'banana']
for fruit in fruits:
if fruit == 'orange':
continue
print(fruit)
banana
1
2
3
4
5
6
7
8
9
10
# 用range()函数生成等差数列
#只有一个参数时,指定的是stop
for i in range(3):
print(i)
#有两个参数时,指定的分别是start、stop
for i in range(2, 3):
print(i)
#有3个参数时,指定的分别是start、stop和step
for i in range(0, 3, 2):
print(i)
0
1
2
2
0
2
1
2
3
# 使用值为负数的step来创建一个反向数列
for i in range(3, -3, -2):
print(i)
3
1
-1
1
2
3
4
5
6
7
8
# 通过结合使用for...in语句与range()函数来代替while语句
i = 0
while i < 3:
print('while重复3次')
i = i + 1

for i in range(3):
print('for重复3次')
while重复3次
while重复3次
while重复3次
for重复3次
for重复3次
for重复3次

2.5 序列切片

1
2
3
4
5
6
7
8
# 对字符串切片
greeting = 'good morning'
print(greeting[:])
print(greeting[6:])
print(greeting[:4])
print(greeting[3:7])
print(greeting[3:7:2])
print(greeting[::2])
good morning
orning
good
d mo
dm
go onn
1
2
3
4
# 反向切片
greeting = 'good morning'
print(greeting[4::-1])
print(greeting[::-1])
 doog
gninrom doog

2.6 解析式

2.6.1 列表解析式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#创建列表的普通方式
numbers = []
for i in range(10):
numbers.append(i)
print(numbers)
# 或
numbers = list(range(10))
print(numbers)
#使用列表解析式创建
numbers = [i for i in range(10)]
print(numbers)
numbers = [i**2 for i in range(10)]
print(numbers)
numbers = ['hi' for i in range(10)]
print(numbers)
numbers = [i for i in range(10) if i % 2 != 0]
print(numbers)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
['hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi']
[1, 3, 5, 7, 9]
1
2
3
4
5
6
7
8
9
10
11
# 对比列表解析式与传统for迭代方法
# 列表解析式
numbers = [(i, j) for i in range(2) for j in range(3)]
print(numbers)

# for迭代
numbers = []
for i in range(2):
for j in range(3):
numbers.append((i, j))
print(numbers)
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]

2.6.2 字典解析式

1
2
3
4
5
# 通过字典解析式创建字典
mapping = {i: i**2 for i in range(10)}
print(mapping)
mapping = {i: i**2 for i in range(10) if i**2>40}
print(mapping)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
{7: 49, 8: 64, 9: 81}

2.6.3 集合解析式

1
2
3
# 通过集合解析式创建集合
numbers = {i for i in range(10)}
print(numbers)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

2.6.4 生成器解析式

1
2
3
4
5
6
7
#使用生成器来进行迭代
numbers = (i for i in range(3))
for i in numbers:
print(i)
print('第一次迭代完成')
for i in numbers:
print(i)
0
1
2
第一次迭代完成

2.7 函数

2.7.1 定义函数

1
2
3
4
# 定义一个没有任何参数和功能的函数
def nothing():
pass
nothing()
1
2
3
4
# 定义一个无参数,输出一个单词的函数
def say_hi():
print('Hi')
say_hi()
Hi
1
2
3
4
5
6
# 给函数加上参数
def say_hi(name):
print('Hi,', name)

say_hi('Daming')

Hi, Daming
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 没有return语句,则在函数执行结束之后自动返回None
def greet(clock):
if clock < 12:
return 'good morning'
elif clock < 18:
return 'good afternoon'
elif clock < 21:
return 'good evening'
else:
return 'good night'
greeting = greet(13)
print(greeting)

#对比
def say_hi():
print('Hi')
print(say_hi())
good afternoon
Hi
None

2.7.2 函数的参数

1
2
3
4
5
6
7
# 位置参数
def pos_abc(a, b, c):
print('a is', a)
print('b is', b)
print('c is', c)

pos_abc(1, 3, 5)
a is 1
b is 3
c is 5
1
2
3
4
5
6
7
# 关键字参数
def pos_abc(a, b, c):
print('a is', a)
print('b is', b)
print('c is', c)

pos_abc(b=3, a=1, c=5)
a is 1
b is 3
c is 5
1
2
3
4
5
6
7
# 混合使用位置参数和关键字参数
def pos_abc(a, b, c):
print('a is', a)
print('b is', b)
print('c is', c)

pos_abc(1, c=5, b=3)
a is 1
b is 3
c is 5
1
2
3
4
5
6
7
# 指定参数默认值
def pos_abc(a, b=3, c=10):
print('a is', a)
print('b is', b)
print('c is', c)

pos_abc(1, 3)
a is 1
b is 3
c is 10
1
2
3
4
5
6
7
8
# 选择传入新参数代替默认值
def pos_abc(a, b, c=10):
print('a is', a)
print('b is', b)
print('c is', c)

pos_abc(1, 3, 5)

a is 1
b is 3
c is 5
1
2
3
4
5
6
7
8
# 定义所有参数都带默认值的函数
def pos_abc(a=1, b=3, c=5):
print('a is', a)
print('b is', b)
print('c is', c)

pos_abc()

a is 1
b is 3
c is 5
1
2
3
4
5
6
7
8
# 用*收集位置参数
def print_args(*args):
print(args)
print_args(1, 2 ,3)
# 以及
def print_args(*args):
print(args)
print_args()
(1, 2, 3)
()
1
2
3
4
5
# 用**收集关键字参数
def print_kwargs(**kwargs):
print(kwargs)

print_kwargs(a=1, b=2)
{'a': 1, 'b': 2}

2.7.3 匿名函数

1
2
3
4
5
6
7
8
# 用lambda关键字定义匿名函数
func = lambda x: x**2
print(func(2))
#或
greet = lambda: print('hello')
pos_ab = lambda a,b: print(a + b)
greet()
pos_ab(1, 2)
4
hello
3

2.7.4 闭包与装饰器

1
2
3
4
5
6
7
# 闭包
def outer():
def inner():
print("I'm inner func")
print("I'm outer func")
inner()
outer()
I'm outer func
I'm inner func
1
2
3
4
5
6
7
8
9
#将outer()函数的返回值指定为inner()函数本身
def outer():
def inner():
print("I'm inner func")
print("I'm outer func")
return inner
func = outer()
print('下面执行func')
func()
I'm outer func
下面执行func
I'm inner func
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 创建一个新的函数say_hi()作为参数放进outer()函数
def outer(func):
def inner():
func()
print("I'm inner func")
print("I'm outer func")
return inner

def say_hi():
print('Hi!')

say_hi = outer(say_hi)
print('下面执行say_hi')
say_hi()
print('再次执行say_hi')
say_hi()
I'm outer func
下面执行say_hi
Hi!
I'm inner func
再次执行say_hi
Hi!
I'm inner func
1
2
3
4
5
6
7
8
9
10
11
12
# 根据放进工厂函数的不同的变量,生产出有不同作用的函数
def factory(n):
def multiply(m):
return n * m
return multiply

x2 = factory(2)
print(x2(2))
print(x2(3))
x10 = factory(10)
print(x10(2))
print(x10(3))
4
6
20
30
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 将代码改写为装饰器的形式
def outer(func):
def inner():
func()
print("I'm inner func")
print("I'm outer func")
return inner

@outer
def say_hi():
print('Hi!')

print('下面执行say_hi')
say_hi()
print('再次执行say_hi')
say_hi()
I'm outer func
下面执行say_hi
Hi!
I'm inner func
再次执行say_hi
Hi!
I'm inner func

2.7.5 高阶函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 映射
def plus2(x):
return x + 2
numbers = [1, 3, 5, 6]
new_numbers = map(plus2, numbers)
print(new_numbers)
print(list(new_numbers))
# 等效于
def plus2(x):
return x + 2
numbers = [1, 3, 5, 6]
new_numbers = [plus2(n) for n in numbers]
print(new_numbers)
#用匿名函数来实现
numbers = [1, 3, 5, 6]
new_numbers = map(lambda x: x + 2, numbers)
print(new_numbers)
print(list(new_numbers))
<map object at 0x7fa310300ed0>
[3, 5, 7, 8]
[3, 5, 7, 8]
<map object at 0x7fa310300c90>
[3, 5, 7, 8]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 过滤
def lt_5(x):
return x < 5

numbers = [1, 3, 5, 6]
new_numbers = filter(lt_5, numbers)
print(new_numbers)
print(list(new_numbers))
# 等效于
def lt_5(x):
return x < 5

numbers = [1, 3, 5, 6]
new_numbers = [n for n in numbers if lt_5(n)]
print(new_numbers)
<filter object at 0x7fa310300cd0>
[1, 3]
[1, 3]

面向对象基础

2.8.2 类和继承

1
2
3
4
5
6
7
8
9
# 初始化方法
class Student:
def __init__(self, name, age, deposit):
self.name = name
self.age = age
self.__deposit = deposit

xiaoming = Student('小明', 12, 1000)
print(xiaoming.name)
小明
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 Student:
def __init__(self, name, age, deposit):
self.name = name
self.age = age
self.__deposit = deposit

def do_homework(self):
# 做作业
answer = self.__calculate(1, 1)
print('做完作业了,答案是', answer)

def wash_dishes(self, n_dishes):
# 洗碗
self.__deposit = self.__deposit + n_dishes * 10
print('洗过碗了,又赚', n_dishes * 10, '元,现在有', self.__deposit)

def __calculate(self, a, b):
# 珠心算
print('悄悄算算术,不告诉别人')
return a + b

xiaoming = Student('小明', 12, 1000)
xiaoming.do_homework()
xiaoming.wash_dishes(1)
xiaoming.wash_dishes(5)
xiaoming.wash_dishes(3)
悄悄算算术,不告诉别人
做完作业了,答案是 2
洗过碗了,又赚 10 元,现在有 1010
洗过碗了,又赚 50 元,现在有 1060
洗过碗了,又赚 30 元,现在有 1090
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 创建一个父类Animal以及子类Dog和Cat,通过继承创建衍生类的新功能
class Animal:
def breathe(self):
print('动物需要呼吸')

class Dog(Animal):
def woof(self):
print('汪汪汪')

class Cat(Animal):
def meow(self):
print('喵喵喵')
#将Dog类和Cat类实例化
speike = Dog()
tom = Cat()
speike.breathe()
tom.breathe()
#Dog类和Cat类都继承自Animal类,它们都有breathe()方法
speike.woof()
tom.meow()
动物需要呼吸
动物需要呼吸
汪汪汪
喵喵喵
1
2
3
4
5
6
7
# 尝试创建一个Mouse类,用以覆盖父类的方法
class Mouse(Animal):
def breathe(self):
print('老鼠也需要呼吸')
jerry = Mouse()
jerry.breathe()

老鼠也需要呼吸