简体   繁体   English

Python中类似字典的对象,允许设置任意属性

[英]Dictionary-like object in Python that allows setting arbitrary attributes

What I want to do in my code: 我想在我的代码中做什么:

myobj = <SomeBuiltinClass>()
myobj.randomattr = 1
print myobj.randomattr
...

I can implement a custom SomeClass that implements __setattr__ __getattr__ . 我可以实现一个实现__setattr__ __getattr__的自定义SomeClass。 But I wonder if there is already a built-in Python class or simple way to do this? 但我想知道是否已经有内置的Python类或简单的方法来做到这一点?

You can just use an empty class: 你可以使用一个空类:

class A(object): pass

a = A()
a.randomattr = 1

I like using the Bunch idiom for this. 我喜欢使用束语成语。 There are list of variations and some discussion here . 有变化的名单和一些讨论在这里

One solution is to use mock's: 一种解决方案是使用mock:

from mock import Mock
myobj = Mock()
myobj.randomattr = 1
print myobj.randomattr

Second solution is to use namedtuple: 第二种解决方案是使用namedtuple:

from collections import namedtuple
myobj = namedtuple('MyObject', '')
myobj.randomattr = 1
print myobj.randomattr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java - 将字节数组转换为 python 类字典 object - Java - Converting byte array to a python dictionary-like object Python:数据框中的类字典对象到新数据框 - Python: Dictionary-like object in dataframe to new dataframe C ++中的Python字典式结构? - Python dictionary-like structure in C++? 在Python中解析类似字典的URL参数 - Parsing dictionary-like URL parameters in Python 在 Python 中将具有类似字典表示的字符串转换为字典 - Transform string with dictionary-like representation into dictionary in Python python中是否有一个函数(或如何)以类似字典的字符串转义双引号? - is there a function in python (or how ) to escape a double quotes in dictionary-like string? 保存按键排序的类似于架子字典的对象 - Save Shelf Dictionary-like object sorted by keys Python(或一般的CS)中的循环或分层字典式数据结构? - A cyclical or hierarchical dictionary-like data structure in Python (or in CS in general)? 在Python中使用类似字典的索引获取矩阵元素 - getting matrix element using dictionary-like index in Python 类似于字典的类,其键可以像属性和预定义属性一样进行获取/设置 - Dictionary-like class with keys that can be get/set like attributes and pre-defined attributes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM