gpt4 book ai didi

Python 风格 : Formating multiple, 冗长的类声明

转载 作者:行者123 更新时间:2023-11-30 23:37:41 24 4
gpt4 key购买 nike

我有一个类 (content.MyClass),其中存储了大量有关细菌的事实。我多次调用它,以定义多种类型的细菌。它不是很优雅,但相当快、可读且模块化(易于添加更多细菌)。

问题:我应该有更好的方法吗?

import content
def myMethod():
bacteria = {} #A dictionary I fill with 'Bacteria Name':object

bacteria['Staph Aureus'] = content.MyClass(
bug_type = ['gram+'],
virulence = ['Protein A', 'TSST-1', 'exfoiative toxin', 'enterotoxin'],
labs = ['catalase+', 'coagulase+']
)
bacteria['Staph Epidermidis'] = content.MyClass(
bug_type = ['gram+'],
sx = ['infects prosthetic devices']
)
#Etc. about 25 more times.
return bacteria

(脚注:我知道 PEP 8 说我应该缩进所有内容以与“MyClass(”对齐,但这在这里不起作用,因为某些列表非常长。此外,每个列表中还有更多变量类;我在这里的示例中修剪了它们。)

最佳答案

Question: is there a better way I should do this?

您正在考虑solving the wrong problem.

创建你的类(class)data-driven:将代码与数据分开。从数据源加载定义;像 JSON 或 YAML 文件这样简单的东西就可以正常工作。

When doing data-driven programming, one clearly distinguishes code from the data structures on which it acts, and designs both so that one can make changes to the logic of the program by editing not the code but the data structure.

http://www.faqs.org/docs/artu/ch09s01.html

关于Python 风格 : Formating multiple, 冗长的类声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15263163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com