【问题标题】:Why does import a class from a module run a lists of that class object? [duplicate]为什么从模块中导入一个类会运行该类对象的列表? [复制]
【发布时间】:2022-10-02 02:50:43
【问题描述】:

所以我有一个这样的module.py:

import dataclass

@dataclass
class A:
  x: int
  y: int

  def big_method(self):
      do_big_stuff(x,y)

LIST_OF_A = [ A(2,3), B(4,5) ]

为什么当我在我的 script.py 中时

from module import A

script.py 实际运行并实例化了 LIST_OF_A ?我修复它的唯一方法是将文件与类定义和 LIST_OF_A 分开。有没有办法将两者结合在一个module.py中?

    标签: python python-3.x


    【解决方案1】:

    每当您导入模块时,python 都会运行该模块。

    在您的模块文件中,您应该在里面编写代码

    def main():
        """Code that is executed only if you run this file itself,
        and ignored if you import it goes here."""
        pass
    
    if __name__ == "__main__":
        main()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 2014-08-17
      • 1970-01-01
      • 2015-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多