首先申明下,本文为笔者学习《Python学习手册》的笔记,并加入笔者自己的理解和归纳总结。
1. 索引__getitem__和__setitem__
>>> class Sample:
def __init__(self, len):
self.L = [x * 2 for x in range(len)]
def __getitem__(self, index):
return self.L[index]
def __setitem__(self, index, value):
self.L[index] = value
>>> s = Sample(5)
>>> s[2] # 索引操作
4
>>> s[0:3] # 切片操作
[0, 2, 4]
>>> s[2] = 1234 # 索引设置
>>> s[2:]
[1234, 6, 8]
>>> for val in s: # for函数调用
print val,
0 2 1234 6 8
2. 迭代器__iter__和next
__iter__
方法用来返回一个迭代器,next
方法返回下一个值。
>>> class Sample:
def __init__(self, len):
self.L = [x * 2 for x in range(len)]
def __iter__(self): # 返回一个迭代器
print "iter",
self.index = -1
return self
def next(self): # next方法,返回当前值
print "next",
if self.index >= (len(self.L) - 1):
raise StopIteration
self.index += 1
return self.L[self.index]
>>> s = Sample(5)
>>> S = iter(s)
iter
>>> next(S)
next
0
>>> next(S)
next
2
3. 包含关系__contains__
__contains__
必须配合迭代器使用,用来查询是否包含。
没有contains
方法
>>> s = Sample(5)
>>> 3 in s # 默认从迭代器中取值比较
iter next next next next next next
False
>>> 2 in s
iter next next
True
增加contains
方法。
>>> class Sample:
def __init__(self, len):
self.L = [x * 2 for x in range(len)]
def __iter__(self):
print "iter",
self.index = -1
return self
def next(self):
print "next",
if self.index >= (len(self.L) - 1):
raise StopIteration
self.index += 1
return self.L[self.index]
def __contains__(self, value):
return value in (10, 20, 30)
>>> s = Sample(5)
>>> 2 in s
False
>>> 10 in s
True
4. 属性引用__getattr__和__setattr__
自定义类,只包含name
属性。
>>> class Sample:
def __getattr__(self, name):
if (name == "name"):
return "Mike"
else:
raise AttributeError
def __setattr__(self, name, value):
if (name == "name"):
print value
else:
raise AttributeError
>>> s = Sample()
>>> s.name # 访问name属性
'Mike'
>>> s.name = "Jack" # 设置name属性
Jack
>>> s.age # 访问age属性,发生异常
Traceback (most recent call last):
File "<pyshell#61>", line 1, in <module>
s.age
File "<pyshell#57>", line 6, in __getattr__
raise AttributeError
AttributeError
>>> s.age = 14 # 设置age属性,发生异常
Traceback (most recent call last):
File "<pyshell#62>", line 1, in <module>
s.age = 14
File "<pyshell#57>", line 11, in __setattr__
raise AttributeError
AttributeError
5. 加法__add__、__radd__和__iadd __
add
方法,实现加法操作
>>> class Sample:
def __init__(self, val):
self.val = val
def __add__(self, val):
print "add", val
return Sample(self.val + val)
def __repr__(self):
return str(self.val)
>>> s = Sample(4)
>>> s + 4 # 加法在实例右边,调用add方法
add 4
8
>>> s # 实例值不改变
4
>>> s += 5 # 自加操作,同样调用add方法
add 5
>>> s # 实例值被修改
9
>>> 4 + s # 不支持加号在实例左边
Traceback (most recent call last):
File "<pyshell#87>", line 1, in <module>
4 + s
TypeError: unsupported operand type(s) for +: 'int' and 'instance'
radd
方法支持加号在实例右边
>>> class Sample:
def __init__(self, val):
self.val = val
def __add__(self, val):
print "add", val
return Sample(self.val + val)
def __radd__(self, val):
print "radd", val
return Sample(self.val + val)
def __repr__(self):
return str(self.val)
>>> s = Sample(4)
>>> 3 + s # 加号在实例左边,使用radd方法
radd 3
7
>>> s
4
iadd
方法实现自加。
>>> class Sample:
def __init__(self, val):
self.val = val
def __add__(self, val):
print "add", val
return Sample(self.val + val)
def __iadd__(self, val):
print "iadd", val
return Sample(self.val + val)
def __repr__(self):
return str(self.val)
>>> s = Sample(4) # 自加使用优先使用iadd方法
>>> s += 6
iadd 6
>>> s
10
6. __call__方法
call
方法使类成为一个可调用函数。
>>> class Sample:
def __call__(self, *pargs, **kargs):
print "call", pargs, kargs
>>> S = Sample()
>>> S(1, 3, 5, name="Mike", age=23)
call (1, 3, 5) {'age': 23, 'name': 'Mike'}
7. 比较表达式__lt__、gt、eq__和__ne
>>> class Sample:
def __init__(self, val):
self.val = val
def __gt__(self, val):
print "gt"
return self.val > val
def __lt__(self, val):
print "lt"
return self.val < val
def __eq__(self, val):
print "eq"
return self.val == val
def __ne__(self, val):
print "ne"
return self.val != val
>>> s = Sample(5)
>>> s > 4 # > 调用gt方法
gt
True
>>> s < 6 # < 调用lt方法
lt
True
>>> 4 == s # == 调用eq方法
eq
False
>>> 4 != s # != 调用ne方法
ne
True
8. 内置函数bool和len
>>> class Sample:
def __init__(self, val):
self.val = val
def __nonzero__(self):
return self.val > 5
def __len__(self):
return self.val
>>> bool(Sample(4)), bool(Sample(6))
(False, True)
>>> len(Sample(4)), len(Sample(6))
(4, 6)
相关文章
Python 数字类型(一)
Python 布尔型(二)
Python 字符串(三)
Python 列表(四)
Python 字典(五)
Python 元组(六)
Python 集合(七)
Python 变量和作用域(八)
Python 语句(九)
Python 函数(十)
Python 类(十一)
Python 模块(十二)
Python 文档(十三)
Python 文件(十四)
Python 异常(十五)
Python 运算符重载(十六)