使用点操作符访问使用漏勺模型类

时间:2017-11-04 23:57:43

标签: python colander

我想知道是否有办法使用点运算符访问使用任何Colander Model类创建的对象。
例如:

class Image(colander.MappingSchema):
    url = colander.SchemaNode(colander.String())
    width = colander.SchemaNode(colander.Int())
    height = colander.SchemaNode(colander.Int())

所以,使用这个模型,如果我反序列化一个json字符串,

image = Image.deserialize("{'url':'xyz', 'width':10, 'height':12}")

我想使用点(。)运算符访问Image的模型属性。

像,

image.url
image.width
image.height

一旦使用点运算符可以访问这些属性,它们应该可以作为IDE代码完成建议使用 这样做的目的是帮助客户轻松获取模型属性,而无需查看模型。

1 个答案:

答案 0 :(得分:0)

我认为你可能会误解,反串行化在这里做什么。此外,您的代码示例对我来说是错误的,因为deserialise期望像对象这样的字典而不是字符串。

但是,要回答您的初步问题,答案是否定的,您无法使用点运算符。这样做的原因是反序列化输入,实际上返回一个字典而不是类型为Image的对象。 See colander's documentation about deserialization

所以以你的例子并纠正它你会有这样的事情:

class Image(colander.MappingSchema):
    url = colander.SchemaNode(colander.String())
    width = colander.SchemaNode(colander.Int())
    height = colander.SchemaNode(colander.Int())

image = Image().deserialize({'url':'xyz', 'width':'10', 'height':'12'})

如果您输入并打印变量image

,会给您以下内容
>>> type(image)
dict
>>> print(image)
{
    'url': 'xyz',
    'height': 12,
    'width': 10
}

请注意将字符串数值转换为整数。