动态创建继承于neomodel.StructuredNode的类

发布于 2025-01-14 22:33:36 字数 941 浏览 2 评论 0原文

Python 的库 neomodel 提供了通过使用名称作为字符串来定义与尚未定义的类的关系的能力,其工作原理如下:

from neomodel import StructuredNode, RelationshipTo
# if Foo is already defined
class Bar (structuredNode):
    rel = RelationshipTo(Foo, 'REL')
# if Foo isn't defined
class Bar(StructuredNode):
    rel = RelationshipTo('Foo', 'REL')

我想在 <运行时并为其提供属性RelationshipTo,该属性应该与未定义尚未类建立关系,所以我这样做了:

Bar = type('Bar', (StructuredNode,), {'rel': RelationshipTo('Foo', 'REL')})

稍后在运行时的某个时刻,我定义 Foo:

Foo = type('Foo', (StructuredNode,), {})

现在如果我想使用我刚刚创建的类:

bar = Bar()

仍然会弹出下一个错误,就好像我还没有定义 Foo 一样:

AttributeError:模块“_pydevd_bundle.pydevd_exec2”没有属性 '富'

注意:如果我至少静态定义 Bar (不在运行时),则不会出现此错误

有人会解释为什么会发生这种情况以及如何在运行时正确定义它们,请问? 我很感激任何帮助!

Python's library neomodel provides the ability to define a relationship with a class that hasn't been defined yet, by using its name as string, which works fine as follows:

from neomodel import StructuredNode, RelationshipTo
# if Foo is already defined
class Bar (structuredNode):
    rel = RelationshipTo(Foo, 'REL')
# if Foo isn't defined
class Bar(StructuredNode):
    rel = RelationshipTo('Foo', 'REL')

I want to create a class in the runtime and provide it with the attribute RelationshipTo, which should make a relationship with undefined yet class, so I did:

Bar = type('Bar', (StructuredNode,), {'rel': RelationshipTo('Foo', 'REL')})

In some point in the runtime later, I define Foo:

Foo = type('Foo', (StructuredNode,), {})

Now if I want to use the class I've just made:

bar = Bar()

The next error still pops up as if I haven't defined Foo:

AttributeError: module '_pydevd_bundle.pydevd_exec2' has no attribute
'Foo'

Note: This error doesn't appear if I at least define Bar statically (not in the runtime)

Would someone explain why that happens and how to define them properly in runtime, please?
I appreciate any help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文