Search code examples
pythonfunctionclassinstancedry

Python - create objects of a class without repeating myself while creating


I am new to python and i have a quick question.

How can I avoid repeating my self when I declare the Class instances x1 x2 ..

I tried it with a list but then I wasn't able to create a file for each object after. And not all parameters are the same for my objects, d[0] is counting up.

Any smart idea to get rid of repeating myself here?

thanks in advance

class TestClass(object):
    def __init__(self, a, b, c: int):
        self.a = a
        self.b = b
        self.c = c

    def __str__(self):
        return f" a= {self.a} b = {self.b} c = {self.c}"

def func1():
    a = input("a: ")
    b = input("b: ")
    return a, b

def func2():
    return 100, 90, 80, 70

c = func1()
d = func2()

x1 = TestClass(c[0], c[1], d[0])
x2 = TestClass(c[0], c[1], d[1])
x3 = TestClass(c[0], c[1], d[2])
x4 = TestClass(c[0], c[1], d[3])
h = {"a": x1,"b": x2, "c": x3, "d": x4}
for key, value in h.items():
    with open(f"Name {key}.txt","w") as f:
        f.write(str(value))


OUTPUT:

#a: Anton
#b: Bernd
#
# four files Name a - d.txt were created
# file 1: a= Anton b = Bernd c = 100
# file 2: a= Anton b = Bernd c = 90
# file 3: a= Anton b = Bernd c = 80
# file 4: a= Anton b = Bernd c = 70

Solution

  • You should iterate on the return value (tuple) of the func2 function (so on the d variable) with the enumerate function. The enumerate function returns the value and the related index of the iterator (Eg.: https://realpython.com/python-enumerate/). Then you can add the element for your (empty) dict. You should use the chr function to define the letters based on the index. The lowercase a is the 97.

    Related code part:

    c = func1()
    d = func2()
    h = {}
    for idx, value in enumerate(d):
        h[chr(97 + idx)] = TestClass(c[0], c[1], d[idx])
    
    for key, value in h.items():
        with open(f"Name {key}.txt", "w") as f:
            f.write(str(value))
    

    NOTE:

    I have written a more compact version of code. You can check it if you are interested in it.

    Code:

    class TestClass(object):
        def __init__(self, a, b, c: int):
            self.a = a
            self.b = b
            self.c = c
    
        def __str__(self):
            return f" a= {self.a} b = {self.b} c = {self.c}"
    
    
    a, b, h, d = input("a: "), input("b: "), {}, [100, 90, 80, 70]
    result = [(chr(97 + idx), TestClass(a, b, d[idx])) for idx, value in enumerate(d)]
    
    for item in result:
        with open(f"Name {item[0]}.txt", "w") as f:
            f.write(str(item[1]))