‘ ** ’在Python中有三个用途
# 第一个,表多少次方
x ** 2 # 表示x的2次方
x ** 3 # 表示x的3次方
# 字符串、列表、元组与一个整数N相乘
'str1' * 3 # 'str1str1str1'
# 第二个,函数定义中通过‘**’,形参数被转化成dict
def func1(**args):
print(args)
func1(a=0, b='haha') # 输出{'a': 0, 'b': 'haha'}
# 第三个,函数调用中通过‘**’传入dict
dict1 = {'jj':0, 'kk':'haha'}
func1(**dict1) # 输出 {'jj': 0, 'kk': 'haha'}
迭代器
http://www.runoob.com/python3/python3-iterator-generator.html
迭代是Python最强大的功能之一,是访问集合元素的一种方式。
迭代器是一个可以记住遍历的位置的对象。
迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。
迭代器有两个基本的方法:iter() 和 next()。
生成器
https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/
1.常规操作
# 斐波拉契数列
def fab(nmax):
n, a, b = 0, 0, 1
l = []
while n < nmax:
l.append(b)
a, b = b, a + b
n = n + 1
return l
2.把函数变成生成器
def fab1(nmax):
n, a, b = 0, 0, 1
while n < nmax:
yield b #
a, b = b, a + b
n = n + 1
for n in fab1(10):
print(n)
自带简单用法函数
endswith()
判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回 True,否则返回 False
assert
assert 2==1,'2不等于1' # 异常时抛出字符串
字典的update方法
# 添加参数
dict1 = {'a':1, 'b':2}
dict1.update({'c':3}) # 传字典
dict1.update(d=4) # 传关键字
print(dict1) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# 更新参数
dict1.update(a=9) # 通过关键字更新
dict1.update({'b':0}) # 通过字典更新
print(dict1) # {'a': 9, 'b': 0, 'c': 3, 'd': 4}
vars
vars返回对象的属性和属性值的字典对象,如果没有参数,就打印当前调用位置的属性和属性值。
class cls1:
a = 1
b = 0
def __init__(self, num):
self.b = num
def func(self, c):
self.num = c
clss = cls1(8)
vars(clss) # Out[22]: {'b': 8}
vars(cls1)
Out[21]:
mappingproxy({'__module__': '__main__',
'a': 1,
'b': 0,
'__init__': <function __main__.cls1.__init__(self, num)>,
'func': <function __main__.cls1.func(self, c)>,
'__dict__': <attribute '__dict__' of 'cls1' objects>,
'__weakref__': <attribute '__weakref__' of 'cls1' objects>,
'__doc__': None})
split()
字符串切片
str1 = 'Welcome to China!'
s = str1.split() # s: ['Welcome', 'to', 'China!']
s = str1.split('o') # s: ['Welc', 'me t', ' China!']
map()
map() 会根据提供的函数对指定序列做映射。python3中map返回迭代器,需要转化才能使用。
1.取出日期中的数字
str1 = '2019-3-31'
year,month,day = map(int, str1.split('-')) # year=2019,month=3...
2.计算依次列表元素的平方
# 构建函数
def f(x):
return x ** 2
list(map(f, [1,2,3,4,5])) # [1, 4, 9, 16, 25]
# 用匿名函数lambda实现
list(map(lambda x: x ** 2, [1,2,3,4,5])) # # [1, 4, 9, 16, 25]
strip
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。http://www.runoob.com/python/att-string-strip.html
字符,列表、字典排序,文件名排序
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
sorted(students, key=lambda student : student[2])
Out[74]: [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
# 文件名排序
dirList = os.listdir('C:\\Users\wyxkx\Desktop\modify_sets\JPEGImages')
dirList.sort(key = lambda x: int(x[:-4]))
OUT: ['00001.jpg',
'00002.jpg',
'00003.jpg',
'00004.jpg',
'00005.jpg',
'00006.jpg']
.all()
判断元素中是否存在None、0、’ '、False,只要存在就返回False
a = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[6, 7, 4, 1]])
a < 9
Out[40]:
array([[ True, True, True, True],
[ True, True, True, True],
[ True, True, True, True]])
(a < 9).all()
Out[37]: True
(a < 8).all()
Out[38]: False
# 用于判断数据是否异常
# 要求a中的数据必须都小于等于8,否则报错
assert((a < 9).all())
assert((a <= 8).all())
class类相关
对象属性需要调用方法后才生效
class H:
a = 0 # 类属性a
def __init__(self):
pass
def f(self):
self.a = 4 # 修改类属性
self.b = 1 # b属于对象属性吧
print(self.a)
print(self.b)
h = H()
H.a # 类属性
Out: 0
H.b # 类直接调用对象属性 报错
Out: AttributeError: type object 'H' has no attribute 'b'
h.a # 对象调用类属性
Out: 0
h.b # 对象调用方法的属性 报错,b还不存在,f执行后b才存在
Out: AttributeError: 'H' object has no attribute 'b'
h.f() # 执行方法
Out: 4 1
h.b # 对象调用方法的属性,正确,因为b已存在
Out: 1
h.a
Out: 4
H.a # 对象属性并没有修改类的属性
Out: 0
self表示一个具体的实例本身,cls表示这个类本身
单例模式(一个类只实例化同一个对象)
一个类多次生成(实例化)对象,所有对象都是跟第一次实例化的对象一样。用途:如多个分公司(类)都在生产同一件产品(对象),不能因为分公司(类)不同而产品(对象)不同。
#单例模式,结合__new__方法
class SingleCase(object):
__instance = None # 类属性,用于保存对象地址,保证只执行一次new方法
__first_init = False # 类属性,保存初始化标志,保证只有一次初始化
#这里的name,age只是为了配合init方法的参数,因为首先执行new,如果缺少参数会报错
#cls指这个类,而self指这个类实例的对象
# 在实例化的过程中,类先调用__new__方法,返回该类的实例对象,作为__init__的self
# 这个实例对象就是__init__方法的第一个参数self,即self是__new__的返回值。
def __new__(cls, name, age): # cls就是指SingleCase这个类
#读取类属性,如果当前类还没有过创建对象
if not cls.__instance:
#修改类属性,用基类new方法创建对象
cls.__instance = object.__new__(cls) # 可用super().__new__(cls)
return cls.__instance #返回对象
# 同一个对象应该只保留第一次初始化
def __init__(self, name, age):
if not self.__first_init: # 如果没有初始化
self.age = age
self.name = name
self.__first_init = True # 标志已初始化,若下次再被初始化if将不成立
a = SingleCase('张三', 20)
print(a)
print(a.name)
print(a.age)
#单例模式,始终只能创建同一个对象,只初始化一次
b = SingleCase('李四', 23)
print(b) # id应该与a的一样,本来就是同一个对象
print(b.name) # 属性只保留第一次初始化的值
print(b.age)
OUT:
<__main__.SingleCase object at 0x000000000298F588>
张三
20
<__main__.SingleCase object at 0x000000000298F588>
张三
20
@staticmethod和@classmethod
共同点:
使用@staticmethod或@classmethod的方法,可以不需要实例化,直接使用classname.function()来调用。
区别:
首先要明白self表示一个具体的实例本身,cls表示这个类本身。
@staticmethod不需要self和自身类的cls参数,就跟使用函数一样。
@classmethod也不需要self参数,但第一个参数需要是表示自身类的cls参数。
类对象的字典__dict__
python中__dict__存储了该对象的一些属性。类和实例分别拥有自己的__dict__,且实例会共享类的__dict__。
添加和更新对象属性(用__dict__)
# 定义一个类
class yyy(object):
_defaults = {
"a": 'aa',
"b": 'bb',
"c": 'cc',}
def __init__(self, **kwargs):
self.__dict__.update(self._defaults) # set up default values
self.__dict__.update(kwargs) # and update with user overrides
# 查看类属性构成的字典
vars(yyy)
Out[40]:
mappingproxy({'__module__': '__main__',
'_defaults': {'a': 'aa', 'b': 'bb', 'c': 'cc'},
'__init__': <function __main__.yyy.__init__(self, **kwargs)>,
'__dict__': <attribute '__dict__' of 'yyy' objects>,
'__weakref__': <attribute '__weakref__' of 'yyy' objects>,
'__doc__': None})
# 实例化一个类并添加和更新对象的属性
y = yyy(**{'d':'dd', 'a':'aaaaa'})
# 查看对象属性构成的字典
vars(y)
Out[46]: {'a': 'aaaaa', 'b': 'bb', 'c': 'cc', 'd': 'dd'} # 更新a,添加d
# 类的属性并没有改变(有点多此一举)
vars(yyy)
Out[47]:
mappingproxy({'__module__': '__main__',
'_defaults': {'a': 'aa', 'b': 'bb', 'c': 'cc'},
'__init__': <function __main__.yyy.__init__(self, **kwargs)>,
'__dict__': <attribute '__dict__' of 'yyy' objects>,
'__weakref__': <attribute '__weakref__' of 'yyy' objects>,
'__doc__': None})
函数装饰器
装饰器(Decorators)是 Python 的一个重要部分。简单地说:他们是修改其他函数的功能的函数。
python3基本数据类型
不可变数据(3 个):Number(数字)、String(字符串)、Tuple(元组);
可变数据(3 个):List(列表)、Dictionary(字典)、Set(集合)。