简体   繁体   English

Python Class 有很多实例

[英]Python Class With Lots of Instances

I need to define a class and lots of instances (more than 30, but 3 of them are given in the code) to be able to share them between python module files.我需要定义一个 class 和许多实例(超过 30 个,但其中 3 个在代码中给出)以便能够在 python 模块文件之间共享它们。 I have problem with the following code (simplified):我对以下代码有疑问(简化):

class class1:
    def __init__(self, var1):
        self.var1 = var1

    def read_file():
        try:
            f = open('/file1.txt')
            read_text = f.readlines()
            abc1 = class1((read_text[0]))
            abc2 = class1((read_text[1]))
            abc3 = class1((read_text[2]))
    
        except:
            abc1 = class1("text_1")
            abc2 = class1("text_2")
            abc3 = class1("text_3")


class1.read_file()

def1 = class1("abc")
def2 = class1("def")
def3 = class1("hjk")

print(def1.var1)
print(abc1.var1)
print(abc2.var1)

It gives the error:它给出了错误:

NameError: name 'abc1' is not defined

I tried to define instances in the class in order to avoid defining instances for them and making the code long.我试图在 class 中定义实例,以避免为它们定义实例并使代码变长。

What is the pythonic way to define more than 30 instances via a class?通过 class 定义 30 多个实例的 pythonic 方式是什么? What is the solution for defining the instances in the class?在 class 中定义实例的解决方案是什么?

Content of the file1.txt: file1.txt 的内容:

a
b
c
d
e

Does this help:这有帮助吗:

class MyClass:

    def __init__(self, var):
        self.var = var


with open('/file1.txt') as f:
    objects = [MyClass(line) for line in f]

print(objects[0].var)
print(objects[1].var)

(let's give PEP8 name to the class) To define "many instances in pythonic way" you may want to use list comprehension. (让我们给类起 PEP8 名称)要定义“pythonic 方式的许多实例”,您可能需要使用列表理解。

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

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