python中attr_python之attr

面向对象之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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值