是否可以在Python中创建匿名对象? [英] Is it possible to create anonymous objects in Python?
问题描述
我正在调试一些Python,该Python需要一个对象列表作为输入,每个对象都有一些属性.
I'm debugging some Python that takes, as input, a list of objects, each with some attributes.
我想对一些测试值进行硬编码-假设,列出了四个对象的列表,这些对象的"foo"属性设置为某个数字.
I'd like to hard-code some test values -- let's say, a list of four objects whose "foo" attribute is set to some number.
还有比这更简洁的方法吗?
Is there a more concise way than this?
x1.foo = 1
x2.foo = 2
x3.foo = 3
x4.foo = 4
myfunc([x1, x2, x3, x4])
理想情况下,我只想说些类似的话:
Ideally, I'd just like to be able to say something like:
myfunc([<foo=1>, <foo=2>, <foo=3>, <foo=4>])
(显然,这是虚构的语法.但是确实有类似的东西真的有用吗?)
(Obviously, that is made-up syntax. But is there something similar that really works?)
注意:这将永远不会被检入.这只是一些一次性的调试代码.因此,不必担心可读性或可维护性.
Note: This will never be checked in. It's just some throwaway debug code. So don't worry about readability or maintainability.
推荐答案
我喜欢Tetha的解决方案,但它不必要地复杂.
I like Tetha's solution, but it's unnecessarily complex.
这里简单一些:
>>> class MicroMock(object):
... def __init__(self, **kwargs):
... self.__dict__.update(kwargs)
...
>>> def print_foo(x):
... print x.foo
...
>>> print_foo(MicroMock(foo=3))
3
这篇关于是否可以在Python中创建匿名对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!