使用特殊方法实现字典
# 使用像字典 dic['xx'] 带中括号的类使用
# 简要介绍
class Foo:
# ① 对象[xx] 调用的方法
def __getitem__(self, item):
return 'getitem'
# ② 对象[xx] = xxx 调用的方法
def __setitem__(self, key, value):
return 'setitem'
# ③ del 对象[xx] 调用的方法
def __delitem__(self, key):
return 'delitem'
obj = Foo()
# ①
ret = obj['test']
# ②
obj['k1'] = 111
# ③
del obj['k1']
#例
class Foo:
def __getitem__(self, item):
# print(type(item),item)
# item.start item.stop item.step
print(type(item))
return 123
def __setitem__(self, key, value):
# key.start key.stop key.step
print(type(key),type(value))
def __delitem__(self, key):
# key.start key.stop key.step
print(type(key))
obj = Foo()
# 传入分片、步长 ,它将是一个slice对象
ret = obj[1:4:2]
print(ret)
iter方法
# iter 方法
class Foo:
def __iter__(self):
yield 1
yield 2
obj = Foo()
# 当对象遇到被迭代时(循环),将访问__iter__方法
for item in obj:
print(item)
super方法
# super方法:主动执行父类方法
class C1:
def f1(self):
print('c1.f1')
return 123
class C2(C1):
def f1(self):
# 主动执行父类的f1方法
ret = super(C2, self).f1()
print('c2.f1')
return ret
obj = C2()
obj.f1()
有序字典实现
# 有序的字典实现(基于dict类)
class MyDict(dict):
def __init__(self):
# 列表是有序的,定义一个空列表接受key值
self.li=[]
# 主动执行父类的__init__方法
super(MyDict, self).__init__()
def __setitem__(self, key, value):
# 当我们去执行 dic['k1'] = 123,会调用__setitem__方法
# 在调用dict类之前,我们将key加入到列表
self.li.append(key)
# 主动执行父类的__setitem__方法
super(MyDict, self).__setitem__(key,value)
def __str__(self):
# 定义一个
temp_list = []
for key in self.li:
value = self.get(key)
temp_list.append("'%s':%s" % (key,value))
temp_list = '{'+','.join(temp_list)+'}'
return temp_list
obj = MyDict()
obj['k1'] = 123
obj['k2'] = 456
print(obj)
==》 {'k1':123,'k2':456}
python单例模式
# python的单例模式
# 1. 使用类方法实现
# 2. 使用静态字段实现
class Foo:
instance = None
def __init__(self,name):
self.name = name
@classmethod
def get_instance(cls):
# cls类名
if cls.instance: # 如果静态字段instance 为真
return cls.instance
else:
obj = cls('alex')
cls.instance = obj #
return obj
obj1 = Foo.get_instance()
print(obj1) # 在这里,类的静态字段instance值已经被该变
obj2 = Foo.get_instance()
print(obj2)
# obj1与obj2 内存地址相同