Magic Methods
Constructor
__init__
, Class initialization method. Local constructor method is different from the ordinary. It will automatically call the object is created.
Create a constructor
class FooBar():
def __init__(self):
self.somevar = 42
f = FooBar()
f.somevar # 42
Destructor
__del__
This method before the object is destroyed (garbage collected) call, but given not know the exact time of the call, do not use as much as possible __del__
.
Substantial sequence and mapping protocols
**__len__(self)**
This method returns the number of items included in the collection of sequences, is the number of elements, for mapping a bond - the value of the number. If __len__
returns zero (and not implemented __nonzero__
), the object regarded as false (like empty tuples, strings, lists, dictionaries, like) in a boolean context.
**__getitem__(self, key)**
This method returns the value associated with the specified key and.
**__setitem__(self, key, value)**
This method is associated with the linkage to the stored value. So that you can use __getitem__
to get.
**__delitem__(self, key)**
This method is in use on the part of the object __del__
to be invoked when the statement, delete the value associated with the key.
Create an infinite sequence
def check_index(key):
"""
指定的键是否是可接受的索引?
键必须是非负整数,如果不是,将引发TypeError异常。
如果是负数,将引发IndexError异常(因为这个序列的长度是无穷的)。
"""
if not isinstance(key, int): raise TypeError
if key < 0: raise IndexError
class AritmeticSequence():
def __init__(self, start=0, step=0):
"""[summary]
初始化这个算数序列
Keyword Arguments:
start {number} -- 序列中的第一个值 (default: {0})
step {number} -- 两个相邻值的差 (default: {0})
changed {dict} -- 一个字典,包含用户修改后的值
"""
self.start = start # 存储起始值
self.step = step # 存储步长值
self.changed = {} # 没有任何元素被修改
def __getitem__(self, key):
"""
从算数序列中获取一个元素
"""
check_index(key)
try: return self.changed[key] # 修改过?
except KeyError: # 如果没有修改过
return self.start + key * self.step # 就计算元素的值
def __setitem__(self, key, value):
"""
修改算数序列中的元素
"""
check_index(key)
self.changed[key] = value
s = AritmeticSequence()
for i in range(10):
print(s[i], end=" ")
# 1 3 5 7 9 11 13 15 17 19