面向对象之attr
class Foo(object):
item = 123
def __setattr__(self, key, value):
print(key, value)
def __getattr__(self, item):
print(item)
obj = Foo()
obj.x = 123 #x 123
print(obj.item) #123
※attr的应用
class Local(object):
def __init__(self):
# 初始化 得到self.storage = {},每次执行类的__setattr__方法,而不会覆盖之前的键值对
object.__setattr__(self, "storage", {})
def __setattr__(self, key, value):
self.storage[key] = value
def __getattr__(self, key):
return self.storage.get(key)
local = Local() # 实例化local对象,执行__init__方法,执行object.__setattr__的方法:self.storage = {}
local.x1 = 123 # 自动执行__setattr__方法,self.storage = {"x1": 123}
print(local.x1) # 自动执行__getattr__方法,取字典的值,得到 123
local.x2 = 456 # 自动执行__setattr__方法,self.storage = {"x2": 456}
print(local.x2) # 456
自定义简单版local
import threading
"""
storage = {
1111:{'x1':0},
1112:{'x1':1}
1113:{'x1':2}
1114:{'x1':3}
1115:{'x1':4}
}
"""
class Local(object):
def __init__(self):
object.__setattr__(self,'storage',{})
def __setattr__(self, key, value):
ident = threading.get_ident()
if ident in self.storage:
self.storage[ident][key] = value
else:
self.storage[ident] = {key:value}
def __getattr__(self, item):
ident = threading.get_ident()
if ident not in self.storage:
return
return self.storage[ident].get(item)
local = Local()
def task(arg):
local.x1 = arg
print(local.x1)
for i in range(5):
t = threading.Thread(target=task,args=(i,))
t.start()
执行结果
0
1
2
3
4
加强版local
import threading
"""
storage = {
1111:{'x1':[]},
1112:{'x1':[]}
1113:{'x1':[]}
1114:{'x1':[]}
1115:{'x1':[]},
1116:{'x1':[]}
}
"""
class Local(object):
def __init__(self):
object.__setattr__(self, 'storage', {})
def __setattr__(self, key, value):
ident = threading.get_ident()
if ident in self.storage:
self.storage[ident][key].append(value)
else:
self.storage[ident] = {key: [value, ]}
def __getattr__(self, item):
ident = threading.get_ident()
if ident not in self.storage:
return
return self.storage[ident][item][-1]
local = Local()
def task(arg):
local.x1 = arg
print(local.x1)
for i in range(5):
t = threading.Thread(target=task, args=(i,))
t.start()