Instance()在Python中做什么?

2024-09-29 19:36:43 发布

您现在位置:Python中文网/ 问答频道 /正文

这行在python中做什么?你知道吗

user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)

请注意,UserMagics是在IPython.core.magics.__init__.py中定义的空类,如下所示:

@magics_class
class UserMagics(Magics):
    """Placeholder for user-defined magics to be added at runtime.

上面的定义和这个定义有什么区别?你知道吗

user_magics = UserMagics()

注意,正如Blender在下面指出的,这是trailets包的一部分,而不是基本Python。你知道吗


Tags: instancepycorenonetrue定义initipython
1条回答
网友
1楼 · 发布于 2024-09-29 19:36:43

Instance^{} package的一部分。根据文件:

In short, traitlets let the user define classes that have

  1. Attributes (traits) with type checking and dynamically computed default values
  2. Traits emit change events when attributes are modified
  3. Traitlets perform some validation and allow coercion of new trait values on assignment. They also allow the user to define custom validation logic for attributes based on the value of other attributes.

下面是这个包的一个示例,具体使用Instance

from traitlets import HasTraits, Int, Instance

class Foo(object):
    pass

class MyObject(HasTraits):
    num = Int()
    foo = Instance(Foo, allow_none=True)

if __name__ == '__main__':
    # works
    a = MyObject()
    a.num = 10
    a.foo = Foo()

    # works
    b = MyObject()
    b.num = 5
    b.foo = None

    # breaks
    c = MyObject()
    c.num = -1
    c.foo = object()  # The 'foo' trait of a MyObject instance must be a Foo or None, but a value of type 'object' was specified.

相关问题 更多 >

    热门问题