考虑这个简单的例子:
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.nameThis 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.nameThis prints "hooked" as expected.
更多推荐
发布评论