python - 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
解决方案
您应该使用函数迭代函数的返回值 ( 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]))
推荐阅读
- javascript - 从 super 继承属性
- javascript - JavaScript 使用 atom ,使用 es6 类时出错
- reactjs - 在 eslintrc.json 中关闭 eslint 规则
- django - Django下拉表单提交无效
- hibernate - Hibernate 单向多对多不插入连接表
- r - 如何在忽略某些字符的同时按名称选择列?
- java - 如何创建嵌套的 JSON 响应
- cefsharp - Pepperflash 在 Cefsharp 版本 65.0.0.0 中不起作用
- css - Gatsby v2 网站无法正确加载 CSS
- javascript - jQuery .each 自动更新并创建全局变量?