python – 在棉花糖中循环导入

python – 在棉花糖中循环导入,第1张

概述我有两个彼此相关的对象.我希望能够通过浏览相关属性来访问另一个对象. 例如. A.b_relationship.obj.some_property 如何在不创建循环导入的情况下执行此 *** 作? # lib.pyclass Relationship(object): def __init__(self, obj): self.obj = obj# a.pyclass 我有两个彼此相关的对象.我希望能够通过浏览相关属性来访问另一个对象.

例如. A.b_relationship.obj.some_property

如何在不创建循环导入的情况下执行此 *** 作?

# lib.pyclass Relationship(object):    def __init__(self,obj):        self.obj = obj# a.pyclass A(object):    b_relationship = Relationship(B)# b.pyclass B(object):    a_relationship = Relationship(A)

为清楚起见,我添加了这个额外的例子.显然,sqlAlchemy使用backref属性解决了这个问题.我不确定在不破坏它的工作方式的情况下将这种东西应用到棉花糖中是多么可行.也许我需要改变我的心态?

from marshmallow import Schemafrom marshmallow.fIElds import Stringfrom project.database import dbclass PersonModel(db.Model):    name = db.Column(db.String)class PetModel(db.Model):    name = db.Column(db.String)    owner = db.relationship('PersonModel',backref='pets')class PersonSchema(Schema):    name = fIElds.String(init_arg='some value')    pets = fIElds.Relationship(related_schema=PetSchema)class PetSchema(Schema):    name = fIElds.String()    owner = fIElds.Relationship(related_schema=PersonSchema)
解决方法 从这里:
http://marshmallow.readthedocs.org/en/latest/nesting.html#two-way-nesting

查看字符串如何用于该类; AuthorSchema引用’BookSchema’:

class AuthorSchema(Schema):    # Make sure to use the 'only' or 'exclude' params    # to avoID infinite recursion    books = fIElds.nested('BookSchema',many=True,exclude=('author',))    class Meta:        fIElds = ('ID','name','books')class BookSchema(Schema):    author = fIElds.nested(AuthorSchema,only=('ID','name'))    class Meta:        fIElds = ('ID','Title','author')

我假设在你的情况下,你想用many = False做同样的事情.我从未使用过棉花糖,但在Django中,它类似,我们使用类似“my_app.MyClass”的类路径而不是MyClass来避免循环导入.

总结

以上是内存溢出为你收集整理的python – 在棉花糖中循环导入全部内容,希望文章能够帮你解决python – 在棉花糖中循环导入所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1193511.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存