Python - 创建 class 的对象而无需在创建时重复自己

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

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

当我声明 Class 个实例 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

快速回答

  • 使用函数,当你需要做一些需要你大量输入的事情或者你需要重复做一些事情然后把它打包成一个函数。

    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)函数。你可以看到我调用了从 int 97 开始的函数。 那是因为ASCII值是字母a --> asciitable.com.


其他改进

有趣的是,我给出的解决方案是使用函数,这与我建议您为改进脚本所做的完全相反,即删除函数:)。

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

使用词典理解

非常强大的工具,速度快(可以 运行 加快 For 循环)和超级 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))

您应该使用 enumerate 函数迭代 func2 函数(d 变量)的 return 值 (tuple) .枚举函数return是迭代器的值和相关索引(例如: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]))