python中內(nèi)置類型添加屬性問題詳解
python中內(nèi)置類型添加屬性問題?
最近項目 進行重構一些代碼:
寫代碼過程中會遇到一個問題,我希望通過內(nèi)置類型生成的對象 添加屬性,但是添加總是失敗.
obj = object() obj.name = 'frank'
報錯如下:
Traceback (most recent call last):
File input, line 2, in
AttributeError: 'object' object has no attribute 'name'
普通對象綁定屬性
我們知道python 語言的動態(tài)性, 是允許可以直接在是一個實例添加屬性的。
class Animal: def eat(self): pass def sleep(self): pass
在python console 里面運行,可以看到是可以正常添加屬性name
>>> animal = Animal() >>> animal.name='dog' >>> animal.name 'dog'
對比這兩個類的不同點:
class Animal(object): def __init__(self): # print(sorted(dir(self))) res = set(dir(self)) - set(dir(object)) print(res) print('########' * 10) res = set(dir(object)) - set(dir(self)) print(res) pass
結果如下:
{'__module__', '__weakref__', '__dict__'}
################################################
set()
發(fā)現(xiàn)self
多了三個魔術方法。 我們來重點關注 __dict__
方法,我們知道一個對象的屬性,一般放在 這個屬性上面的。 但是object 的實例 沒有這個屬性。
def main(): obj = object() try: print(obj.__dict__) except AttributeError as e: print("ERROR:", e) animal = Animal() print(animal.__dict__, type(animal.__dict__)) animal.name = 'animal' animal.age = 10 print(animal.__dict__)
結果如下:
在 animal 對象中, 屬性已經(jīng)存放在了 __dict__
中。 而obj對象就沒有 __dict__
這個屬性。
而我有一個大膽的想法,有沒有辦法可以直接在obj 實例上把 __dict__
綁定到這個實例obj 上面呢?
在python console 里面嘗試下:
>>> obj = object() >>> >>> obj.__dict__ = dict() Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'object' object has no attribute '__dict__' >>> setattr(obj,'__dict__',dict()) Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'object' object has no attribute '__dict__'
發(fā)現(xiàn)并不能綁定成功,python 里面不允許這樣綁定。
在python中 所有內(nèi)置對象 list,dict,set ,object 等等,這些內(nèi)置對象,不允許在里面添加 屬性,方法等。
這樣做是一個不好的行為,一旦你對內(nèi)置對象做了修改,其他引用內(nèi)置對象的代碼,是否會受到影響呢 ? 這是一個不可預期的行為。
解決方法
比較好的做法:想綁定一個屬性 在一個對象上面??梢宰远x一個類。然后綁定屬性,而不是在內(nèi)置類型生成的對象進行綁定。
class Object(object): pass >>> obj = Object() >>> obj.__dict__ {} >>> obj.name='frank' >>> obj.__dict__ {'name': 'frank'} >>> obj.name 'frank'
從網(wǎng)上找到一個解決方案在內(nèi)置類型上面可以添加方法 ,但是記得不要在生產(chǎn)環(huán)境這樣玩!
import ctypes class PyObject(ctypes.Structure): class PyType(ctypes.Structure): pass ssize = ctypes.c_int64 if ctypes.sizeof(ctypes.c_void_p) == 8 else ctypes.c_int32 _fields_ = [ ('ob_refcnt', ssize), ('ob_type', ctypes.POINTER(PyType)), ] def sign(klass, func_name): def _(function): class SlotsProxy(PyObject): _fields_ = [('dict', ctypes.POINTER(PyObject))] name, target = klass.__name__, klass.__dict__ proxy_dict = SlotsProxy.from_address(id(target)) namespace = {} ctypes.pythonapi.PyDict_SetItem( ctypes.py_object(namespace), ctypes.py_object(name), proxy_dict.dict, ) namespace[name][func_name] = function return _ # method-1 @sign(list, 'mean') def mean(l): return sum(l) / len(l) # # @sign(list, 'max') def mean(l): return max(l) # method-2 sign(list, 'mean')(lambda l: sum(l) / len(l)
總結
不要在python內(nèi)置對象上面添加方法和屬性。因為這種行為是不可預期的,最好的做法繼承內(nèi)置對象,在派生子類中添加屬性,方法等。
到此這篇關于python中內(nèi)置類型添加屬性問題詳解的文章就介紹到這了,更多相關python添加屬性內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python將一個CSV文件里的數(shù)據(jù)追加到另一個CSV文件的方法
今天小編就為大家分享一篇Python將一個CSV文件里的數(shù)據(jù)追加到另一個CSV文件的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07