本文介紹了從標準庫向 Python 字典添加屬性的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想知道是否可以向 Python 字典添加屬性?
I was wondering if you could add an attribute to a Python dictionary?
class myclass():
def __init__():
self.mydict = {} # initialize a regular dict
self.mydict.newattribute = "A description of what this dictionary will hold"
>>> AttributeError: 'dict' object has no attribute 'newattribute'
setattr(self.mydict, "attribute", "A description of what this dictionary will hold"
>>> AttributeError: 'dict' object has no attribute 'newattribute'
有沒有辦法快速添加我的描述屬性,而不必復制 dict 類和重載構造函數.我以為這很簡單,但我想我錯了.
Is there anyway to quickly add my description attribute without having to copy the dict class and overloading the constructor. I thought it would be simple, but I guess I was wrong.
推薦答案
直接派生自dict
:
class MyDict(dict):
pass
MyDict
實例的行為類似于 dict
,但可以具有自定義屬性:
Instances of MyDict
behave like a dict
, but can have custom attributes:
>>> d = MyDict()
>>> d.my_attr = "whatever"
>>> d.my_attr
'whatever'
這篇關于從標準庫向 Python 字典添加屬性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!