首页 > 解决方案 > Python - 创建类的对象而不在创建时重复自己

问题描述

我是 python 新手,我有一个简单的问题。

当我声明类实例 x1 x2 时,如何避免重复我自己。

我尝试了一个列表,但之后我无法为每个对象创建一个文件。对于我的对象,并非所有参数都相同, d[0] 正在计数。

有什么聪明的主意可以避免在这里重复自己吗?

提前致谢

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


输出:

#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

标签: pythonfunctionclassinstancedry

解决方案


您应该使用函数迭代函数的返回值 ( tuple) func2(等等d变量)enumerate。enumerate 函数返回迭代器的值和相关索引(例如:https ://realpython.com/python-enumerate/ )。然后你可以为你的(空)字典添加元素。您应该使用该chr函数根据索引定义字母。小写字母a是 97。

相关代码部分:

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

笔记:

我写了一个更紧凑的代码版本。如果您对它感兴趣,可以查看它。

代码:

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]))

推荐阅读