2

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
Maximilian
  • 66
  • 9

2 Answers2

2

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]))
milanbalazs
  • 4,811
  • 4
  • 23
  • 45
1

Quick answer

  • Use a Function, when you need to do something that's going to take you a lot of Typing or you need to do something repeatedly then pack it into a function.

    def create_func(fun_1, fun_2):
    
         result = {}
         acii_n = 97
         for item in fun_2:
             name = chr(acii_n)
             acii_n += 1
             class_instance = TestClass(fun_1[0], fun_1[1], item)
             result.setdefault(name, class_instance)
         return result
    
     h = create_func(c, d)
    
    
     for key, value in h.items():
         with open(f"Name {key}.txt","w") as f:
             f.write(str(value))
    
  • chr(i) Function. You can see that I call the function starting at int 97. That's because the ASCII value is the letter a --> asciitable.com.


Additional improvements

Funny enough the solution I gave, which is use a function, is also the exact opposite that I can suggest you to do for improve your script, which is remove the functions :).

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 create_instances(fun_2):
    
    a = input("a: ")
    b = input("b: ")
    user_values = [a, b]
    result = {}
    ascii_n = 97
    for item in fun_2:
        name = chr(ascii_n)
        ascii_n += 1 # Step on the next charactes
        class_instance = TestClass(user_values[0], user_values[1], item)
        result.setdefault(name, class_instance)
    return result


int_values = [100, 90, 80, 70] # Just pack it into a list 
all_instances = create_instances(int_values)


for key, value in all_instances.items():
    with open(f"Name {key}.txt","w") as f:
        f.write(str(value))

Using a Dictionary Comprehension

Very Powerful Tool, fast (can run Faster the For loops) and super Pythonic :) Python Dictionary Comprehension.

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}"


int_values = [100, 90, 80, 70]
a = 'Python'
b = 'WOOW'
user_values = [a, b]
ascii_n = 97
result = {chr(ascii_n+idx): TestClass(user_values[0], user_values[1], item) for idx, item in enumerate(int_values)}

for key, value in result.items():
    with open(f"Name {key}.txt","w") as f:
        f.write(str(value))
Federico Baù
  • 6,013
  • 5
  • 30
  • 38