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()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM