如何从主程序导入的类中访问所有变量?

2024-09-27 21:35:01 发布

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

我知道这个问题已经被回答了很多次了,但是答案并不能完全解决我的问题

在我的例子中,我需要在一个由它导入的类中使用来自主程序的屏幕(以及多个其他变量,如level

一个常见的答案是使用变量作为参数。这对我不起作用,因为我不想每次创建一个类时都传递5个以上的参数

另一个答案是使用from main import *。这不起作用,因为有些变量是在导入类之后创建的

有解决办法吗

编辑:这是我的程序的结构:

main.py

import module

screenX = 1000
screenY = 500
...

player = module.Player()

module.py

class Player:
    def __init__(self):
        self.x = screenX
        self.y = screenY
        ...

    def go(self):
        self.x += 1
        if self.touchs(level):
            self.die()

    def touchs(self, object):
        ...

    def die(self):
        ...

我希望这有帮助


Tags: 答案pyimportself程序参数maindef
1条回答
网友
1楼 · 发布于 2024-09-27 21:35:01

A common answer is to use the variables as a parameter. This doesn't work for me as I don't want to pass 5+ parameters every time I make a class.

我认为你低估了这种方法的灵活性。请看以下示例:

main.py

import module

settings = {
    "foo": "bar",
    # ...
}

player = module.Player(settings)
player.print_foo()
settings["foo"] = "baz"
player.print_foo()

module.py

class Player:
    def __init__(self, settings):
        self.settings = settings
    def print_foo(self):
        print(self.settings["foo"])

相关问题 更多 >

    热门问题