0
我有几个变量我想把它们看作常量,因为它们从不改变,并且在我的项目中被大量不同的函数使用。我需要能够从几个不同的模块访问常量,并且我发现的建议建议将常量放入我的config.py
中,然后在每个模块中使用from config import CONSTANT1
。在几个不相关的函数中使用常量的正确方法
我的问题是这样的:我不确定在这种情况下实际使用常量的最Pythonic方法?下面的示例选项是否正确,或者取决于您想要做什么?有没有不同的正确我没有想到的方式?
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?
我不明白你认为第一个选项是错误的。 –
我真的只是检查它*是否被认为是正确的:)我对函数的理解受到'R'和阅读函数式编程的影响,我对它是否有点混淆了适当地依赖于全局(或者在这种情况下,模块级别)的环境或者如果函数需要自包含。我也有兴趣开始单元测试我的工作(我不知道该怎么做),我不清楚如果依靠一个常量是一个坏主意/最终会引入难以理解的错误 – HFBrowning
IME当你依赖_mutable_全局状态时,单元测试只会变得复杂。常量在程序生命周期中不会改变,因此在函数内引用它们不会增加潜在代码路径的数量。在这方面,它们并不比直接使用文字值更糟糕。 – Kevin