在 Python 中创建一个空对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19476816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating an empty object in Python
提问by Smiles
Are there any shortcuts for defining an empty object in Python or do you always have to create an instance of a custom empty class?
在 Python 中定义空对象是否有任何快捷方式,或者您是否总是必须创建自定义空类的实例?
Edit: I mean an empty object usable for duck typing.
编辑:我的意思是一个可用于鸭子打字的空对象。
采纳答案by aychedee
You can use type to create a new class on the fly and then instantiate it. Like so:
您可以使用 type 动态创建一个新类,然后实例化它。像这样:
>>> t = type('test', (object,), {})()
>>> t
<__main__.test at 0xb615930c>
The arguments to type are: Class name, a tuple of base classes, and the object's dictionary. Which can contain functions (the object's methods) or attributes.
type 的参数是:类名、基类元组和对象的字典。其中可以包含函数(对象的方法)或属性。
You can actually shorten the first line to
您实际上可以将第一行缩短为
>>> t = type('test', (), {})()
>>> t.__class__.__bases__
(object,)
Because by default type creates new style classes that inherit from object.
因为默认情况下,类型会创建从对象继承的新样式类。
type
is used in Python for metaprogramming.
type
在 Python 中用于元编程。
But if you just want to create an instance of object. Then, just create an instance of it. Like lejlot suggests.
但是如果你只是想创建一个对象的实例。然后,只需创建它的一个实例。就像 lejlot 建议的那样。
Creating an instance of a new class like this has an important difference that may be useful.
创建像这样的新类的实例有一个可能有用的重要区别。
>>> a = object()
>>> a.whoops = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'whoops'
Where as:
然而:
>>> b = type('', (), {})()
>>> b.this_works = 'cool'
>>>
回答by lejlot
What do you mean by "empty object"? Instance of class object
? You can simply run
“空对象”是什么意思?类的实例object
? 你可以简单地运行
a = object()
or maybe you mean initialization to the null reference? Then you can use
或者你的意思是初始化空引用?然后你可以使用
a = None
回答by Will
One simple, less-terrifying-looking way to create an empty(-ish) object is to exploit the fact that functions are objects in Python, including Lambda Functions:
创建空(-ish)对象的一种简单的、看起来不那么可怕的方法是利用函数是 Python 中的对象这一事实,包括 Lambda 函数:
obj = lambda: None
obj.test = "Hello, world!"
For example:
例如:
In [18]: x = lambda: None
In [19]: x.test = "Hello, world!"
In [20]: x.test
Out[20]: 'Hello, world!'
回答by Vlad Bezden
Yes, in Python 3.3 SimpleNamespacewas added
是的,在 Python 3.3中添加了SimpleNamespace
Unlike object, with SimpleNamespace you can add and remove attributes. If a SimpleNamespace object is initialized with keyword arguments, those are directly added to the underlying namespace.
与对象不同,使用 SimpleNamespace 可以添加和删除属性。如果 SimpleNamespace 对象使用关键字参数初始化,则这些参数会直接添加到基础命名空间中。
Example:
例子:
import types
x = types.SimpleNamespace()
x.happy = True
print(x.happy) # True
del x.happy
print(x.happy) # AttributeError. object has no attribute 'happy'
回答by qben
All the proposed solutions are somewhat awkward.
所有提出的解决方案都有些尴尬。
I found a way that is not hacky but is actually according to the original design.
我找到了一种不笨拙但实际上是根据原始设计的方法。
>>> from mock import Mock
>>> foo = Mock(spec=['foo'], foo='foo')
>>> foo.foo
'foo'
>>> foo.bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/.../virtualenv/local/lib/python2.7/site-packages/mock/mock.py", line 698, in __getattr__
raise AttributeError("Mock object has no attribute %r" % name)
AttributeError: Mock object has no attribute 'bar'
回答by D z
Constructs a new empty Set object. If the optional iterable parameter is supplied, updates the set with elements obtained from iteration. All of the elements in iterable should be immutable or be transformable to an immutable using the protocol described in section Protocol for automatic conversion to immutable.
构造一个新的空 Set 对象。如果提供了可选的 iterable 参数,则使用从迭代中获得的元素更新集合。iterable 中的所有元素都应该是不可变的,或者可以使用协议一节中描述的协议将其转换为不可变的,以便自动转换为不可变的。
Ex:
前任:
myobj = set()
for i in range(1,10): myobj.add(i)
print(myobj)
回答by Basj
You said it in the question, but as no answer mentioned it with code, this is probably one of the cleanest solutions:
你在问题中说过,但没有答案用代码提到它,这可能是最干净的解决方案之一:
class Myobject:
pass
x = Myobject()
x.test = "Hello, world!" # working