【问题标题】:Define Python class in separate file在单独的文件中定义 Python 类
【发布时间】:2018-07-23 05:01:08
【问题描述】:
# File 1
me = MongoEngine(app) # I want to use my instance of MongoEngine to define new classes like the example in File 2

# File 2
class Book(me.Document):
    title = StringField(null=False, unique=True)
    year_published = IntField(null=True)

在新文件中创建新类时,如何将实例 me.Document 作为对象定义传递。如果我将它们放在同一个文件中,它会起作用吗?

【问题讨论】:

  • 你为什么不直接导入File 2
  • 你已经尝试了什么?在这种情况下,me 与您可以导入的任何其他 Python 对象没有什么不同。

标签: python-3.x oop instance-variables abstraction


【解决方案1】:

就像文件中的任何 Python 对象一样,me 可以被导入。你可以这样做:

import file1
class Book(file1.me.Document):
    #Do what you want here!

希望我有所帮助!

【讨论】:

    【解决方案2】:

    我认为选择的答案并不完全正确。

    看来File1.py是你执行的主脚本File2.py 是一个模块,其中包含您希望在 File1.py 中使用的 class

    同样基于previous question of the OP我想建议以下结构:

    File1.py 和 File2.py 位于同一个目录

    File1.py

    import MongoEngine
    from File2 import Book
    
    me = MongoEngine(app)
    
    # according to the documentation
    # you do need to pass args/values in the following line
    my_book = Book(me.Document(*args, **values))
    # then do something with my_book
    # which is now an instance of the File2.py class Book
    

    文件2.py

    import MongoEngine
    
    class Book(MongoEngine.Document):
    
        def __init__(self, *args, **kwargs):
            super(Book, self).__init__(*args, **kwargs)
            # you can add additional code here if needed
    
        def my_additional_function(self):
            #do something
            return True
    

    【讨论】:

    • 超类实际上是我为避免循环引用而寻找的!
    【解决方案3】:

    File 2 中执行me 对象的导入:

    from file1 import me
    
    
    class Book(me.Document):
        pass
        # ...
    

    【讨论】:

    • 这很好用,但是如果我想在 File1 中使用 Book 类,我会遇到循环引用。本例中的文件 1 是我的 main.py?
    • 这与传递 Python 变量的关系不大,而与应用程序的结构有关。应用标准的循环解析方法,例如在函数级别导入 file2,或者更好地将依赖于 file2.py 的实现从 file1.py 移除到单独的实现文件中,从而打破循环依赖。
    • 此外,您可以简单地避免使用 from x import y 构造来自动解析循环导入。这是关于 Python 导入如何工作以及 importfrom 有何不同的推荐答案:stackoverflow.com/questions/744373/…
    • 在我看来 file1 是执行的脚本,因此我不会将 file1 导入到 file2 中,我会以相反的方式进行。这也解释了循环引用问题。不需要循环引用/导入
    猜你喜欢
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多