Python在创建类时不重复自己创建类的对象

2024-06-16 11:59:20 发布

您现在位置: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

Tags: 对象selfinputreturndeffilex1x2
2条回答

您应该使用enumerate函数迭代func2函数的返回值(tuple)(对d变量也是如此)。枚举函数返回迭代器的值和相关索引(例如:https://realpython.com/python-enumerate/)。然后可以为(空)dict添加元素。应该使用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]))

快速回答

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

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

使用字典理解

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

相关问题 更多 >