在导入Python模块之前,如何更改变量的值?

发布于 2025-02-03 14:23:45 字数 689 浏览 5 评论 0原文

假设我有一个具有一些变量的config.py文件,

# config.py
LIFE = 1
MONEY = 200

我将必须导入一个在自身内部使用这些变量的函数,

# game.py
from config import LIFE, MONEY

def live():
    if MONEY < 1000:
        print("Money:", MONEY)
        return 'GAME OVER'
    
    else:
        print('Money:', MONEY)
        return 'LIVED ONE DAY'

并假设我进入了测试阶段,并且我必须测试“ game.live”函数。但是我在game.py或config.py中都没有写入权限。您如何认为在调用“ game.live”函数之前,我如何更改货币变量的价值,从而使金钱的价值也会在'game.live'函数中变化?

例如,

# test.py
from config import MONEY, LIFE
MONEY = 20000000000000

from game import live
print(live())

>> Money: 20000000000000
>> LIVED ONE DAY

Suppose I have a config.py file that has some variables,

# config.py
LIFE = 1
MONEY = 200

And I will have to import a function which uses those variables within itself,

# game.py
from config import LIFE, MONEY

def live():
    if MONEY < 1000:
        print("Money:", MONEY)
        return 'GAME OVER'
    
    else:
        print('Money:', MONEY)
        return 'LIVED ONE DAY'

And suppose I went into testing phase, and I have to test the 'game.live' function. But I have no write permissions in either of the game.py or the config.py . How do you think I could change the value of, say, MONEY variable before calling the 'game.live' function such that the value of MONEY also changes in the 'game.live' function?

For example,

# test.py
from config import MONEY, LIFE
MONEY = 20000000000000

from game import live
print(live())

>> Money: 20000000000000
>> LIVED ONE DAY

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

開玄 2025-02-10 14:23:46

我认为最好的方法是使用数据库和管理其内容的文件。

您可以通过搜索“ sqlite3示例python”来找到一些python的示例。

祝你好运

I think the best way is to use a database and a file that manages his content.

You can find some examples for python by searching for "sqlite3 example python" it's simple to use.

Good luck with this

栀梦 2025-02-10 14:23:45

如果您更改事物的工作方式,那么可以进行测试:

# game.py
import config

def live():
    if config.MONEY < 1000:
        print("Money:", config.MONEY)
        return 'GAME OVER'
    
    else:
        print('Money:', config.MONEY)
        return 'LIVED ONE DAY'

类似地更改测试:

# test.py
import config
config.MONEY = 20000000000000

from game import live
print(live())

输出根据要求

If you change how things work, then its possible to test:

# game.py
import config

def live():
    if config.MONEY < 1000:
        print("Money:", config.MONEY)
        return 'GAME OVER'
    
    else:
        print('Money:', config.MONEY)
        return 'LIVED ONE DAY'

Similarly change the test:

# test.py
import config
config.MONEY = 20000000000000

from game import live
print(live())

Output as requested

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文