Tricks-in-python

本文最后更新于:2023年6月19日 晚上

装饰器-@classmethod 和@staticmethod

将方法定义成类方法和静态方法。

https://zhuanlan.zhihu.com/p/28010894
可以看看这篇文章

生成器

通过函数方式创建

通过yield关键字将一个函数变成generator。例如:
函数的定义:

1
2
3
4
5
6
7
def fib(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
return 'done'

生成器的定义:

1
2
3
4
5
6
7
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'

两者的差别在于生成器将函数的print(b)改为yield byield可以翻译为生成,即基于某次计算生成某个元素,而不是提前存储了该元素。
函数式的generator一般采用for循环来获取元素,也可以通过next()来获取下一个元素的值,例如:

1
2
3
4
5
6
7
8
9
>>> for n in fib(6):
... print(n)
...
1
1
2
3
5
8

如果要获取return的内容,可以捕获StopIteration错误,返回值包含在StopIterationvalue中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> g = fib(6)
>>> while True:
... try:
... x = next(g)
... print('g:', x)
... except StopIteration as e:
... print('Generator return value:', e.value)
... break
...
g: 1
g: 1
g: 2
g: 3
g: 5
g: 8
Generator return value: done

面向对象编程

访问限制

实例的变量以__xxx双下划线开头,没有以__双下划线结尾的,则该变量为私有变量,外部一般无法访问。例如:self.__name = name
如果变量名是双下划线开头、双下划线结尾,__xxx__是特殊变量而不是私有变量。私有变量的方式可以避免外部对实例内部数据的修改,可以做参数检查。
如果需要获取或修改内部的数据,可以增加getset的方法。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Student(object):
#构造函数
def __init__(self, name, score):
self.__name = name
self.__score = score
#get方法
def get_name(self):
return self.__name
def get_score(self):
return self.__score
#set方法
def set_score(self, score):
#参数检查
if 0 <= score <= 100:
self.__score = score
else:
raise ValueError('bad score')

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!