在几个不相关函数中使用常量的正确方法

2024-04-18 08:46:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几个变量,我想作为常量处理,因为他们永远不会改变,并在我的项目吨不同的函数使用。我需要能够访问几个不同模块中的常量,我发现的建议建议是将常量放入我的config.py中,然后在每个模块中使用from config import CONSTANT1。你知道吗

我的问题是:在这种情况下,我不确定使用常量的方式是什么?下面的示例选项是否正确,或者可能取决于您要做什么?有没有一种我没有想到的不同的方法?你知道吗

def fake_function(x, y):
    # Problem: function relies on the module-level environment for an input
    # (Seems sloppy)
    return (x + y + CONSTANT1)

def fake_function2(x, y, z=CONSTANT1):
    # Problem: seems redundant and as if there was no point in declaring a constant
    # Also you end up with way too many parameters this way
    return (x + y + z)

class Fakeness(object):
    def __init__(self):
        self.z = CONSTANT1
    def fake_sum(self, x, y):
        return (x + y + self.z)
        # Problem: I suspect this might be the correct implementation - but 
        # I hope not because my understanding of OOP is weak :) I also don't
        # think this helps me with my many functions that have nothing to do
        # with each other but happen to use the same constants?

Tags: 模块theselfconfigreturndefwithfunction
1条回答
网友
1楼 · 发布于 2024-04-18 08:46:02

是的,你可以这样做,这很常见。同样常见的,而且通常更方便的是使用/滥用类作为名称空间,这样您就有一个东西要导入,一个地方可以潜在地更改常量的工作方式。我会这样做:

class Settings(object):
    TIMEOUT = 4
    RETRY = 2
    SECRET_KEY = 'foobar'

然后,您可以导入设置,传递设置,或者如果以后需要,甚至可以更改请求或设置时发生的情况设置.FOO通过使用getattr或元类hackery。只是一个很好的未来证明。你知道吗

相关问题 更多 >