基本的Python模块设计问题

1 投票
1 回答
526 浏览
提问于 2025-04-15 16:23

我有:

lib/
lib/__init__.py
lib/game.py

__init__.py 文件中,我想定义一个变量,这个变量可以被 lib 里面的任何类访问,像这样:

BASE = 'http://www.whatever.com'

然后在 game.py 文件中,在 Game 类里访问这个变量:

class Game:

def __init__(self, game_id):
    self.game_id = game_id

    url = '%syear_%s/month_%s/day_%s/%s/' % (lib.BASE, year, month, day, game_id)

嗯,很明显 'lib.BASE' 这样用是不对的——这里应该怎么做呢?有没有更整洁、更符合 Python 风格的方法来处理我称之为包级全局变量的东西?

1 个回答

4

请查看 http://docs.python.org/tutorial/modules.html#intra-package-references

你可以有一个 lib/settings.py 文件,其中包含以下内容

BASE = 'http://www.whatever.com'

然后你可以这样说

from settings import *

game.py 文件中,你应该能够写

url = '%syear_%s/month_%s/day_%s/%s/' % (BASE, year, month, day, game_id)

撰写回答