简体   繁体   English

从另一个python文件导入对象作为列表

[英]Importing objects from another python file as a list

I have a file (Crop_Library.py) containing a list of objects with various attributes (same number for all):我有一个文件 (Crop_Library.py),其中包含具有各种属性的对象列表(所有对象的编号相同):

from Crop import Crop

Basil = Crop("Basil", 3, 0, 5, 10, 5)
Lettuce = Crop("Lettuce", 3, 4, 5, 10, 7)
Kale = Crop("Kale", 1, 2, 3, 4, 5)

I would like for my GUI program (GUI.py) to read all the objects in Crop_Library.py and store them in a list so that my GUI can list them in a Combobox (so they also need to be converted to strings, or just read the crop.name string, which is the first attribute for all).我希望我的 GUI 程序 (GUI.py) 读取 Crop_Library.py 中的所有对象并将它们存储在一个列表中,以便我的 GUI 可以将它们列在一个组合框中(因此它们也需要转换为字符串,或者只是读取crop.name 字符串,这是所有属性的第一个属性)。

For now, importing is the question.目前,进口是个问题。 However as an FYI, I would like to add edit functionality to another part of my GUI in the future such that the objects can be created/edited/deleted.但是,作为仅供参考,我想在将来向 GUI 的另一部分添加编辑功能,以便可以创建/编辑/删除对象。 I am open to using a json file instead of a python file to store these objects if that is a better approach - I am new to python and just very lost so any guidance is appreciated.如果这是一种更好的方法,我愿意使用 json 文件而不是 python 文件来存储这些对象 - 我是 python 的新手,只是非常迷茫,因此感谢任何指导。

Thanks in advance!提前致谢!

There are a few solutions: 有几种解决方案:

  1. Create a new .txt file, store the lists and read from them 创建一个新的.txt文件,存储列表并从中读取

  2. Create a code that reads from that file 创建一个从该文件读取的代码

If you use JSON, what you read won't be Crop objects. 如果使用JSON,则读取的内容不会是Crop对象。 You could turn the input into Crop objects after reading the data. 您可以在读取数据后将输入转换为Crop对象。

Here's how you could have a list upon import of what you have: 导入内容后,您可以通过以下方式获得列表:

from Crop import Crop

Basil = Crop("Basil", 3, 0, 5, 10, 5)
Lettuce = Crop("Lettuce", 3, 4, 5, 10, 7)
Kale = Crop("Kale", 1, 2, 3, 4, 5)

crops = [ Basil, Lettuce, Kale ]

or more concisely, if you don't need the object names, which you shouldn't... 或更简而言之,如果不需要对象名称,则不需要...

from Crop import Crop

crops = [
    Crop("Basil", 3, 0, 5, 10, 5),
    Crop("Lettuce", 3, 4, 5, 10, 7),
    Crop("Kale", 1, 2, 3, 4, 5,)
]

BTW, per proper Python naming conventions, your Crop object names should be lowercase. 顺便说一句,根据正确的Python命名约定,您的Crop对象名称应为小写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM