Search code examples
pythonpython-3.xclassinstance

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. 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.

What is the pythonic way to define more than 30 instances via a class? What is the solution for defining the instances in the class?

Content of the file1.txt:

a
b
c
d
e

Solution

  • 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.