实例化一个Enthought特征的默认实例(Instantiating a default instance for an Enthought trait)

编程入门 行业动态 更新时间:2024-10-27 06:29:51
实例化一个Enthought特征的默认实例(Instantiating a default instance for an Enthought trait)

考虑这个简单的例子:

from traits.api import Instance, Str, HasTraits class Person(HasTraits): name = Str("hooked") class Chair(HasTraits): sitting = Instance(Person) t = Chair() print t.sitting.name

由于t.sitting评估为None因此失败。 Enthought的traits模块将强制t.sitting的类型是Person但是如何让默认人员在这里实例化? 我不想将任何参数传递给Chair(**kwargs)我希望自动完成此操作。 hooked了print语句的预期输出。

Consider this simple minimal example:

from traits.api import Instance, Str, HasTraits class Person(HasTraits): name = Str("hooked") class Chair(HasTraits): sitting = Instance(Person) t = Chair() print t.sitting.name

This fails since t.sitting evaluates to None. Enthought's traits module will enforce that the type of t.sitting is a Person but how can I get the default person to instantiate here? I don't want to pass any parameters to the Chair(**kwargs) I'd like this to be done automatically. The expected output to the print statement is hooked.

最满意答案

这很有趣。 根据Instance docstring,如果klass是一个类并且未指定arg和kw,则调用Instance将返回None。 arg和kw的默认值为None,因此调用Instance(Person)将返回None,就像您看到的那样。 我通过将“kw = {}”或“args = []”添加到Instance调用中来让您的代码工作。

from traits.api import Instance, Str, HasTraits class Person(HasTraits): name = Str("hooked") class Chair(HasTraits): sitting = Instance(Person, kw = {}) t = Chair() print t.sitting.name

如预期的那样打印“挂钩”。

This is interesting. According to the Instance docstring, calling Instance will return None if klass is a class and arg and kw are not specified. arg and kw have default values of None and so calling Instance(Person) is returning None like you are seeing. I got your code to work by adding "kw = {}" or "args = []" to the Instance call.

from traits.api import Instance, Str, HasTraits class Person(HasTraits): name = Str("hooked") class Chair(HasTraits): sitting = Instance(Person, kw = {}) t = Chair() print t.sitting.name

This prints "hooked" as expected.

更多推荐

本文发布于:2023-08-07 14:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464775.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   特征   Enthought   Instantiating   instance

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!