简体   繁体   English

如何在Python中为多个类和函数指定许多默认值?

[英]How to specify many default values for several classes, functions in Python?

This is not my code but I have a similar problem: 这不是我的代码,但是我有一个类似的问题:

https://gist.github.com/songrotek/0c64d10cab5298c63cd0fc004a94ba1f https://gist.github.com/songrotek/0c64d10cab5298c63cd0fc004a94ba1f

There are many parameters I want to edit and change in one central place (in the most semantic way possible) and then use to construct classes, run the main program etc.. Because I don't want to put everything in one file (it's too big, I need modules and different namespaces) and declare global variables. 我想在一个中央位置编辑和更改许多参数(以尽可能最语义的方式),然后使用它们构造类,运行主程序等。因为我不想将所有内容都放在一个文件中(太大,我需要模块和不同的名称空间)并声明全局变量。 Having to edit the code for setting some parameters doesn't seem to be a good solution. 必须编辑用于设置某些参数的代码似乎不是一个好的解决方案。

class Example:
    def __init__(self, *initial_data, **kwargs):
        for dictionary in initial_data:
            for key in dictionary:
                setattr(self, key, dictionary[key])
        for key in kwargs:
            setattr(self, key, kwargs[key])

Using constructors like this for being able to use dictionaries for init doesn't seem to be transparent enough. 使用这样的构造函数能够使用字典进行初始化似乎不够透明。

What are possible solutions for this problem? 有什么可能的解决方案? It's still code mostly used by me and rather small, so it should be a good compromise between lightweight/appropriate for the size and still easy to use and comfortable. 它仍然是我最常用的代码,相当小,因此应该在轻便/适合大小的同时又易于使用和舒适之间做出很好的折衷。

A common way to handle this is a configuration file that is being read by ConfigParser . 一种常见的处理方法是ConfigParser读取的配置文件。

Here is an example: 这是一个例子:

# configuration.ini
[Example1]

constant1: 1
constant2: 2

[Example2]

c1: 'one'
c2: 'two'

# test.py
from ConfigParser import ConfigParser

conf = ConfigParser()
conf.read('configuration.ini')

def configure_instance(instance):
    for i in conf.items(type(instance).__name__):
        setattr(instance, i[0], i[1])

class Example1(object):
    def __init__(self):
        configure_instance(self)

class Example2(object):
    def __init__(self):
        configure_instance(self)


e1 = Example1()
e2 = Example2()
print vars(e1)
print vars(e2)

# {'constant1': '1', 'constant2': '2'}
# {'c2': "'two'", 'c1': "'one'"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM