如何创建具有属性的内联对象?

发布于 2024-08-07 09:30:29 字数 361 浏览 3 评论 0原文

在 Javascript 中它会是:

var newObject = { 'propertyName' : 'propertyValue' };
newObject.propertyName;  // returns "propertyValue"

但是在 Python 中相同的语法会创建一个字典,而这不是我想要的

new_object = {'propertyName': 'propertyValue'}
new_object.propertyName  # raises an AttributeError

In Javascript it would be:

var newObject = { 'propertyName' : 'propertyValue' };
newObject.propertyName;  // returns "propertyValue"

But the same syntax in Python would create a dictionary, and that's not what I want

new_object = {'propertyName': 'propertyValue'}
new_object.propertyName  # raises an AttributeError

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

够钟 2024-08-14 09:30:29
obj = type('obj', (object,), {'propertyName' : 'propertyValue'})

两种type函数使用

obj = type('obj', (object,), {'propertyName' : 'propertyValue'})

there are two kinds of type function uses.

暮年 2024-08-14 09:30:29

Python 3.3 为此添加了 SimpleNamespace 类确切目的:

>>> from types import SimpleNamespace

>>> obj = SimpleNamespace(propertyName='propertyValue')
>>> obj
namespace(propertyName='propertyValue')

>>> obj.propertyName
'propertyValue'

除了构建对象的适当构造函数之外,SimpleNamespace 还定义了 __repr____eq__ (记录在 3.4 中)以按预期运行。

Python 3.3 added the SimpleNamespace class for that exact purpose:

>>> from types import SimpleNamespace

>>> obj = SimpleNamespace(propertyName='propertyValue')
>>> obj
namespace(propertyName='propertyValue')

>>> obj.propertyName
'propertyValue'

In addition to the appropriate constructor to build the object, SimpleNamespace defines __repr__ and __eq__ (documented in 3.4) to behave as expected.

初相遇 2024-08-14 09:30:29

彼得的回答

obj = lambda: None
obj.propertyName = 'propertyValue'

Peter's answer

obj = lambda: None
obj.propertyName = 'propertyValue'
小情绪 2024-08-14 09:30:29

我不知道是否有内置的方法来做到这一点,但你总是可以定义一个这样的类:

class InlineClass(object):
    def __init__(self, dict):
        self.__dict__ = dict

obj = InlineClass({'propertyName' : 'propertyValue'})

I don't know if there's a built-in way to do it, but you can always define a class like this:

class InlineClass(object):
    def __init__(self, dict):
        self.__dict__ = dict

obj = InlineClass({'propertyName' : 'propertyValue'})
陪你搞怪i 2024-08-14 09:30:29

我喜欢 Smashery 的想法,但是Python 似乎满足于让你自己修改类:

>>> class Inline(object):
...     pass
...
>>> obj = Inline()
>>> obj.test = 1
>>> obj.test
1
>>>

对我来说在 Python 2.5 中工作得很好。请注意,您必须对从 object 派生的类执行此操作 - 如果您将该行更改为 obj = object,它将不起作用。

I like Smashery's idea, but Python seems content to let you modify classes on your own:

>>> class Inline(object):
...     pass
...
>>> obj = Inline()
>>> obj.test = 1
>>> obj.test
1
>>>

Works just fine in Python 2.5 for me. Note that you do have to do this to a class derived from object - it won't work if you change the line to obj = object.

野稚 2024-08-14 09:30:29

SilentGhost 有一个很好的答案,但他的代码实际上创建了一个元类类型的新对象,换句话说,它创建了一个类。类是 Python 中的对象!

obj = type('obj', (object,), {'propertyName' : 'propertyValue'})
type(obj) 

给出

<class 'type'>

要在一行中创建具有 dict 属性(又名属性)的自定义或内置类的新对象,我建议直接调用它:

new_object = type('Foo', (object,), {'name': 'new object'})()

现在

type(new_object) 

是,

<class '__main__.Foo'>

这意味着它是类的对象Foo

我希望它能帮助那些刚接触 Python 的人。

SilentGhost had a good answer, but his code actually creates a new object of metaclass type, in other words it creates a class. And classes are objects in Python!

obj = type('obj', (object,), {'propertyName' : 'propertyValue'})
type(obj) 

gives

<class 'type'>

To create a new object of a custom or build-in class with dict attributes (aka properties) in one line I'd suggest to just call it:

new_object = type('Foo', (object,), {'name': 'new object'})()

and now

type(new_object) 

is

<class '__main__.Foo'>

which means it's an object of class Foo

I hope it helps those who are new to Python.

回眸一遍 2024-08-14 09:30:29

在 Python 中,使用 __init__() 函数声明一个类很容易,该函数可以使用可选参数为您设置实例。如果您不指定参数,您将得到一个空白实例,如果您指定部分或全部参数,您将初始化该实例。

我解释了这里(我评分最高的答案到目前为止)所以我不会重新输入解释。但是,如果您有疑问,请提出,我会回答。

如果您只想要一个其类并不重要的通用对象,您可以这样做:

class Generic(object):
    pass

x = Generic()
x.foo = 1
x.bar = 2
x.baz = 3

一个明显的扩展是添加一个 __str__() 函数来打印有用的内容。

当你想要一本更方便的字典时,这个技巧有时会很有用。我发现输入 x.foo 比输入 x["foo"] 更容易。

It is easy in Python to declare a class with an __init__() function that can set up the instance for you, with optional arguments. If you don't specify the arguments you get a blank instance, and if you specify some or all of the arguments you initialize the instance.

I explained it here (my highest-rated answer to date) so I won't retype the explanation. But, if you have questions, ask and I'll answer.

If you just want a generic object whose class doesn't really matter, you can do this:

class Generic(object):
    pass

x = Generic()
x.foo = 1
x.bar = 2
x.baz = 3

An obvious extension would be to add an __str__() function that prints something useful.

This trick is nice sometimes when you want a more-convenient dictionary. I find it easier to type x.foo than x["foo"].

过去的过去 2024-08-14 09:30:29

另一个可行的选择是使用 namedtuple

from collections import namedtuple

message = namedtuple('Message', ['propertyName'], verbose=True)
messages = [
    message('propertyValueOne'),
    message('propertyValueTwo')
]

Another viable option is to use namedtuple:

from collections import namedtuple

message = namedtuple('Message', ['propertyName'], verbose=True)
messages = [
    message('propertyValueOne'),
    message('propertyValueTwo')
]
一瞬间的火花 2024-08-14 09:30:29
class test:
    def __setattr__(self,key,value):
        return value


myObj = test()
myObj.mykey = 'abc' # set your property and value
class test:
    def __setattr__(self,key,value):
        return value


myObj = test()
myObj.mykey = 'abc' # set your property and value
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文