In [22]: for name,val insignature(f).parameters.items(): ...: print(name,val.kind) ...: a KEYWORD_ONLY b VAR_KEYWORD
可看到参数a的类型为KEYWORD_ONLY,也就是仅仅为关键字参数。
但是,如果f定义为:
deff(a,*b): print(f'a:{a},b:{b}')
查看参数类型:
In [24]: for name,val insignature(f).parameters.items(): ...: print(name,val.kind) ...: a POSITIONAL_OR_KEYWORD b VAR_POSITIONAL
可以看到参数a既可以是位置参数也可是关键字参数。
27使用slice对象
生成关于蛋糕的序列cake1:
In [1]: cake1 =list(range(5,0,-1))
In [2]: b = cake1[1:10:2]
In [3]: b Out[3]: [4, 2]
In [4]: cake1 Out[4]: [5, 4, 3, 2, 1]
再生成一个序列:
In [5]: from random import randint ...: cake2 = [randint(1,100) for _ inrange(100)] ...: # 同样以间隔为2切前10个元素,得到切片d ...: d = cake2[1:10:2] In [6]: d Out[6]: [75, 33, 63, 93, 15]
In [16]: i_am_list = [1,3,5] In [17]: i_am_tuple =tuple(i_am_list) In [18]: i_am_tuple Out[18]: (1, 3, 5)
五、 类和对象
34 是否可调用
检查对象是否可被调用
In [1]: callable(str) Out[1]: True
In [2]: callable(int) Out[2]: True
In [18]: class Student(): ...: def__init__(self,id,name): ...: self.id = id ...: self.name = name ...: def __repr__(self): ...: return'id = '+self.id +', name = '+self.name ...
In [19]: xiaoming =Student('001','xiaoming')
In [20]: callable(xiaoming) Out[20]: False
如果能调用xiaoming(), 需要重写Student类的__call__方法:
In [1]: class Student(): ...: def__init__(self,id,name): ...: self.id = id ...: self.name = name ...: def __repr__(self): ...: return'id = '+self.id +', name = '+self.name ...: def __call__(self): ...: print('I can be called') ...: print(f'my name is {self.name}') ...:
In [2]: t =Student('001','xiaoming')
In [3]: t() I can be called my name is xiaoming
35 ascii 展示对象
调用对象的 __repr__ 方法,获得该方法的返回值,如下例子返回值为字符串
>>>classStudent(): def__init__(self,id,name): self.id = id self.name = name def__repr__(self): return'id = '+self.id +', name = '+self.name
调用:
>>> xiaoming =Student(id='1',name='xiaoming') >>> xiaoming id =1, name = xiaoming >>>ascii(xiaoming) 'id = 1, name = xiaoming'
In [1]: class Student(): ...: def__init__(self,id,name): ...: self.id = id ...: self.name = name ...: def __repr__(self): ...: return'id = '+self.id +', name = '+self.name
In [2]: xiaoming =Student(id='001',name='xiaoming') In [3]: getattr(xiaoming,'name') # 获取xiaoming这个实例的name属性值 Out[3]: 'xiaoming'
40 对象是否有这个属性
In [1]: class Student(): ...: def__init__(self,id,name): ...: self.id = id ...: self.name = name ...: def __repr__(self): ...: return'id = '+self.id +', name = '+self.name
In [2]: xiaoming =Student(id='001',name='xiaoming') In [3]: hasattr(xiaoming,'name') Out[3]: True
In [4]: hasattr(xiaoming,'address') Out[4]: False
41 对象门牌号
返回对象的内存地址
In [1]: id(xiaoming) Out[1]: 98234208
42 isinstance
判断object是否为类classinfo的实例,是返回true
In
[1]: class Student(): ...: def__init__(self,id,name): ...: self.id = id ...: self.name = name ...: def __repr__(self): ...: return'id = '+self.id +', name = '+self.name
In [2]: xiaoming =Student(id='001',name='xiaoming')
In [3]: isinstance(xiaoming,Student) Out[3]: True
43 父子关系鉴定
In [1]: class undergraduate(Student): ...: defstudyClass(self): ...: pass ...: def attendActivity(self): ...: pass
In [2]: issubclass(undergraduate,Student) Out[2]: True
In [3]: issubclass(object,Student) Out[3]: False
In [4]: issubclass(Student,object) Out[4]: True
如果class是classinfo元组中某个元素的子类,也会返回True
In [1]: issubclass(int,(int,float)) Out[1]: True
44 所有对象之根
object 是所有类的基类
In [1]: o =object()
In [2]: type(o) Out[2]: object
45 创建属性的两种方式
返回 property 属性,典型的用法:
classC: def__init__(self): self._x =None
defgetx(self): return self._x
defsetx(self, value): self._x = value
defdelx(self): del self._x # 使用property类创建 property 属性 x =property(getx, setx, delx, "I'm the 'x' property.")
使用python装饰器,实现与上完全一样的效果代码:
classC: def__init__(self): self._x =None
@property defx(self): return self._x
@x.setter defx(self, value): self._x = value
@x.deleter defx(self): del self._x
46 查看对象类型
classtype(name, bases, dict)
传入一个参数时,返回 object 的类型:
In [1]: class Student(): ...: def__init__(self,id,name): ...: self.id = id ...: self.name = name ...: def __repr__(self): ...: return'id = '+self.id +', name = '+self.name ...:
In [2]: xiaoming =Student(id='001',name='xiaoming') In [3]: type(xiaoming) Out[3]: __main__.Student
In [2]: hash([1,2,3]) # TypeError: unhashable type: 'list'
52 一键帮助
返回对象的帮助文档
In [1]: help(xiaoming) Help on Studentin module __main__ object:
class Student(builtins.object) |Methods defined here: | |__init__(self, id, name) | |__repr__(self) | |Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined)
In [2]: for i initer(lst): ...: print(i) ...: 1 3 5
In [1]: class TestIter(object): ...: def__init__(self): ...: self.l=[1,3,2,3,4,5] ...: self.i=iter(self.l) ...: def __call__(self): #定义了__call__方法的类的实例是可调用的 ...: item =next(self.i) ...: print ("__call__ is called,fowhich would return",item) ...: return item ...: def __iter__(self): #支持迭代协议(即定义有__iter__()函数) ...: print ("__iter__ is called!!") ...: return iter(self.l) In [2]: t =TestIter() In [3]: t() # 因为实现了__call__,所以t实例能被调用 __call__ is called,which would return1 Out[3]: 1
In [4]: for e in
TestIter(): # 因为实现了__iter__方法,所以t能被迭代 ...: print(e) ...: __iter__ is called!! 1 3 2 3 4 5
55 打开文件
返回文件对象
In [1]: fo =open('D:/a.txt',mode='r', encoding='utf-8')
In [2]: fo.read() Out[2]: '\ufefflife is not so long,\nI use Python to play.'
mode取值表:
字符
意义
'r'
读取(默认)
'w'
写入,并先截断文件
'x'
排它性创建,如果文件已存在则失败
'a'
写入,如果文件存在则在末尾追加
'b'
二进制模式
't'
文本模式(默认)
'+'
打开用于更新(读取与写入)
56 创建range序列
range(stop)
range(start, stop[,step])
生成一个不可变序列:
In [1]: range(11) Out[1]: range(0, 11)
In [2]: range(0,11,1) Out[2]: range(0, 11)
57 反向迭代器
In [1]: rev =
reversed([1,4,2,3,1])
In [2]: for i in rev: ...: print(i) ...: 1 3 2 4 1
58 聚合迭代器
创建一个聚合了来自每个可迭代对象中的元素的迭代器:
In [1]: x = [3,2,1] In [2]: y = [4,5,6] In [3]: list(zip(y,x)) Out[3]: [(4, 3), (5, 2), (6, 1)]
In [4]: a =range(5) In [5]: b =list('abcde') In [6]: b Out[6]: ['a', 'b', 'c', 'd', 'e'] In [7]: [str(y) +str(x) for x,y inzip(a,b)] Out[7]: ['a0', 'b1', 'c2', 'd3', 'e4']
59 链式操作
from operator import (add, sub)
defadd_or_sub(a, b, oper): return (add if oper =='+'else sub)(a, b)
add_or_sub(1, 2, '-') # -1
60 对象序列化
对象序列化,是指将内存中的对象转化为可存储或传输的过程。很多场景,直接一个类对象,传输不方便。
但是,当对象序列化后,就会更加方便,因为约定俗成的,接口间的调用或者发起的 web 请求,一般使用 json 串传输。