python中內(nèi)置類型添加屬性問題詳解
python中內(nèi)置類型添加屬性問題?
最近項目 進(jìn)行重構(gòu)一些代碼:
寫代碼過程中會遇到一個問題,我希望通過內(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
結(jié)果如下:
{'__module__', '__weakref__', '__dict__'}
################################################
set()
發(fā)現(xiàn)self 多了三個魔術(shù)方法。 我們來重點關(guān)注 __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__)結(jié)果如下:

在 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)置對象的代碼,是否會受到影響呢 ? 這是一個不可預(yù)期的行為。
解決方法
比較好的做法:想綁定一個屬性 在一個對象上面??梢宰远x一個類。然后綁定屬性,而不是在內(nèi)置類型生成的對象進(jìn)行綁定。
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)總結(jié)
不要在python內(nèi)置對象上面添加方法和屬性。因為這種行為是不可預(yù)期的,最好的做法繼承內(nèi)置對象,在派生子類中添加屬性,方法等。
到此這篇關(guān)于python中內(nèi)置類型添加屬性問題詳解的文章就介紹到這了,更多相關(guān)python添加屬性內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python實現(xiàn)錄制全屏和選擇區(qū)域錄屏功能
這篇文章主要介紹了python實現(xiàn)錄制全屏和選擇區(qū)域錄屏功能,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02
Python函數(shù)式編程藝術(shù)之修飾器運用場景探索
本文將詳細(xì)介紹Python修飾器的概念,提供詳細(xì)的示例,并介紹如何使用它們來優(yōu)化和擴展代碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11

