Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

function - 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
question from:https://stackoverflow.com/questions/65850558/python-create-objects-of-a-class-without-repeating-myself-while-creating

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...