我自己学习Python已经有几个星期了,在搜索和阅读整个互联网之后,我仍然不确定如何避免全局变量,思路并在Python中列出正确的方法。仍然有很多嘈杂的含义'关于那个话题(作为一个初学者和非英语母语人士,这很令人困惑)。
目前我的尝试是创建一个实用类,其中包含一种静态的'成员并通过静态方法访问它们,如下面的类:
class StaticLookupTables(object):
# Example luts.
# They can be quite large (but not huge)!
_a = ["A", "B", "C", "D"]
_b = ["a", "b", "c", "d"]
_colors = {
"green": (0.25, 1.00, 0.25, 1.00),
"yellow": (1.00, 1.00, 0.00, 1.00),
"white": (1.00, 1.00, 1.00, 1.00)
}
@staticmethod
def is_in_a(ident):
return True if ident in _a else False
@staticmethod
def is_in_b(ident):
return True if ident in _b else False
@staticmethod
def is_in_c(ident):
return True if ident in _c else False
@staticmethod
def get_socket_color(ident):
try:
return _colors[ident]
except KeyError:
return (0.00, 0.00, 0.00, 0.00)
如果需要,我可以使用以下课程:
from .util import StaticLookupTables as SLT
#
# ... more code ...
#
if SLT.is_in_a(var):
do_things_when_var_is_in_a()
谢谢你,祝你新年快乐。