简体   繁体   English

在 Python 中创建一个空的 object

[英]Creating an empty object in Python

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 中定义空 object 是否有任何快捷方式,或者您是否总是必须创建自定义空 class 的实例?

Edit: I mean an empty object usable for duck typing.编辑:我的意思是一个空的 object 可用于鸭子打字。

You can use type to create a new class on the fly and then instantiate it.您可以使用 type 动态创建一个新类,然后实例化它。 Like so:像这样:

>>> 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. type 的参数是:类名、基类元组和对象的字典。 Which can contain functions (the object's methods) or attributes.其中可以包含函数(对象的方法)或属性。

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'
>>> 

Yes, in Python 3.3 SimpleNamespace was added是的,在 Python 3.3 中添加了SimpleNamespace

Unlike object, with SimpleNamespace you can add and remove attributes.与对象不同,使用 SimpleNamespace 可以添加和删除属性。 If a SimpleNamespace object is initialized with keyword arguments, those are directly added to the underlying namespace.如果 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'

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!'

What do you mean by "empty object"? “空对象”是什么意思? Instance of class object ?object实例? You can simply run你可以简单地运行

a = object()

or maybe you mean initialization to the null reference?或者你的意思是初始化空引用? Then you can use然后你可以使用

a = None

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

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'

See the documentation of unittest.mock here.请在此处查看 unittest.mock 的文档。

Constructs a new empty Set object .构造一个新的空 Set 对象 If the optional iterable parameter is supplied, updates the set with elements obtained from iteration.如果提供了可选的 iterable 参数,则使用从迭代中获得的元素更新集合。 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. iterable 中的所有元素都应该是不可变的,或者可以使用协议一节中描述的协议将其转换为不可变的,以便自动转换为不可变的。

Ex:例如:

myobj = set()
for i in range(1,10): myobj.add(i)
print(myobj)

In my opinion, the easiest way is:在我看来,最简单的方法是:

def x():pass
x.test = 'Hello, world!'

You can use你可以使用

x = lambda: [p for p in x.__dict__.keys()]

Then然后

x.p1 = 2
x.p2 = "Another property"

After之后

x()
# gives
# ['p1', 'p2']

And并且

[(p, getattr(x,p)) for p in x()]
# gives
# [('p1', 2), ('p2', 'Another property')]

If there is a desired type of the empty object, in other words, you want to create it but don't call the __init__ initializer, you can use __new__ :如果有一个空的 object 的期望类型,换句话说,你想创建它但不调用__init__初始化程序,你可以使用__new__

class String(object):
    ...

uninitialized_empty_string = String.__new__(String)

Source: https://stackoverflow.com/a/2169191/6639500 .资料来源: https://stackoverflow.com/a/2169191/6639500

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM