Python 简单裸对象 [英] Python simple naked objects
问题描述
创建可以为其分配属性的裸对象的最简单方法是什么?
What's the easiest way to create a naked object that I can assign attributes to?
具体用例是:我在一个 Django 对象实例上做各种操作,但有时实例是 None(实例上有).在这种情况下,我想创建最简单的假对象,以便我可以为其属性分配值(例如 myobject.foo = 'bar'
).
The specific use case is: I'm doing various operations on a Django object instance, but sometimes the instance is None (there is on instance). In this case I'd like to create the simplest possible fake object such that I can assign values to its attributes (eg. myobject.foo = 'bar'
).
基本上,我正在寻找与这段 Javascript 等效的 Python:
Basically I'm looking for the Python equivalent of this piece of Javascript:
myobject = {}
myobject.foo = 'bar'
我知道我可以为此使用模拟对象/库,但我希望有一个非常简单的解决方案(就像上面的 Javascript 一样简单).有没有办法创建一个裸对象实例?类似的东西:
I know I can use a mock object/library for this, but I'm hoping for a very simple solution (as simple as the Javascript above). Is there a way to create a naked object instance? Something like:
myobject = object()
myobject.foo = 'bar'
推荐答案
你需要先创建一个简单的类:
You need to create a simple class first:
class Foo(object):
pass
myobject = Foo()
myobject.foo = 'bar'
你可以把它做成这样的单线:
You can make it a one-liner like this:
myobject = type("Foo", (object,), {})()
myobject.foo = 'bar'
对type
的调用与之前的class
语句的功能相同.
The call to type
functions identically to the previous class
statement.
如果你想真正极简...
myobject = type("", (), {})()
关键是内置类型(如list
和object
)不支持自定义属性,所以需要使用class
语句或对 type
的 3 参数版本的调用.
The key is that the built-in types (such as list
and object
) don't support user-defined attributes, so you need to create a type using either a class
statement or a call to the 3-parameter version of type
.
这篇关于Python 简单裸对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!