我应该使用类作为全局变量的容器吗
我正在用 pygame 制作一个简单的游戏,我意识到我需要一堆标记、计数和各种全球工作人员。所以我决定定义一个类并像这样使用它:
class Staff():
def __init__(self):
self.modes={'menu':True,'spawning':False,'sprite_change':False}
self.timer=pygame.time.Clock()
self.tick_count=0
在我的游戏循环中,我只为我的所有函数提供一个变量:
def main_loop():
staff=Staff()
while not done:
update_positions(staff)
clear_background(staff)
draw_sprites(staff)
我知道这种方法有效并且非常方便(对我来说),但我想知道这会如何影响我的游戏速度,也许我正在做一些可怕的事情? 非常感谢您的回答。
I were making a simple game in pygame and I realized I need a bunch of markers, counts and all sorts of global staff. So I decided to define a class and use it like this:
class Staff():
def __init__(self):
self.modes={'menu':True,'spawning':False,'sprite_change':False}
self.timer=pygame.time.Clock()
self.tick_count=0
and in my game loop I just give one variable to all my functions:
def main_loop():
staff=Staff()
while not done:
update_positions(staff)
clear_background(staff)
draw_sprites(staff)
I know this method is working and quite convenient (for me), but I wonder how's this going to affect speed of my game, may be I'm doing something horrible?
Many thanks for answering.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请帮自己一个忙,重新考虑您的设计。
首先,您可能认为使用全局变量更容易。您可以传递值,并且可以从每个函数访问它们,而无需使用参数将其传递给它们。但是,当涉及到调试或查找错误或只是在一段时间后查看代码时,全局变量就会变成一场噩梦。因为您很容易忘记这些变量将对其他函数或类产生影响。所以,帮自己一个忙,重新考虑你的设计。
例如,“全局”变量的好地方可能是主类或函数。一切开始的地方。我猜想有一个循环,有些事情会永久重复。从那里您可以将其传递给特定的类或函数。我不知道你的架构,但是全局变量根本没有什么用处。
Please, do yourself a favour and rethink your design.
Firstly you might think that is easier for you to use global variables. You can pass around values and you can access them from every function without passing it to them using parameters. But when it comes to debugging or finding errors or just looking into your code after a while global variables are turning into a nightmare. Because you easily forget where these variables will take impact on other functions or classes. So, do yourself a favour and rethink your design.
A good place for your "global" variables could be for example the main class or function. Where it all begins. I guess there is a loop where some things will be repeated permanently. from there you can pass it to the specific classes or functions. I don't know your architecture, but it is seldom useful to have global variables at all.
虽然我根本不懂 python,但全局变量通常是一个坏主意。我建议使用单例模式。虽然这也不是最好的主意,但它肯定比全局变量更好:
Python 和单例模式
除此之外,你的方法对我来说似乎很好。
While I don't know python at all, globals in general are a bad idea. I suggest the Singleton pattern. While it's not the greatest idea either, it's certainly better than globals:
Python and the Singleton Pattern
Other than that, your approach seems fine to me.