如何在Python中使用属性创建内联对象? [英] How to create inline objects with properties in Python?
本文介绍了如何在Python中使用属性创建内联对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Javascript中为:
var newObject = { 'propertyName' : 'propertyValue' };
newObject.propertyName; // returns "propertyValue"
但是Python中相同的语法会创建一个字典,那不是我想要的
new_object = {'propertyName': 'propertyValue'}
new_object.propertyName # raises an AttributeError
解决方案
obj = type('obj', (object,), {'propertyName' : 'propertyValue'})
有两种type
函数使用. >
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
解决方案
obj = type('obj', (object,), {'propertyName' : 'propertyValue'})
there are two kinds of type
function uses.
这篇关于如何在Python中使用属性创建内联对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文