简体   繁体   English

如何在Python中组织类?

[英]How to Organize Classes in Python?

I've come across an issue that I feel has an extremely simple answer but is hard to explain in a short Google search and I can't find anything about this topic. 我遇到过一个问题,我认为答案非常简单,但很难在简短的谷歌搜索中解释,我找不到任何关于这个主题的内容。

So, in a recent game I've been working on I have multiple types of objects for every block/tile in the game: 所以,在最近的一个游戏中,我一直在努力,我为游戏中的每个块/平铺都有多种类型的对象:

    class Char(object):
        ...
        def update(self):
            ...
        def move(self, direction):
            ...

or 要么

    class Dirt(object):
        ...

and obviously, defining all of these classes in the main program can be very messy , for example, what if I wanted to create an object in the game that had the name "screen" (a computer screen), well this would conflict with my screen class for the actual game window. 显然,在主程序中定义所有这些类可能会非常混乱 ,例如,如果我想在游戏中创建一个名为“screen”(计算机屏幕)的对象,那么这将与我的冲突实际游戏窗口的屏幕类。 And, further more, creating a second module called gameObjects also causes the problem that all my game objects don't have access to variables defined in main. 而且,创建第二个名为gameObjects的模块也会导致我的所有游戏对象无法访问main中定义的变量的问题。

So, how can I organize, or group , my classes? 那么,我如何组织或分组我的课程呢? I'm a beginner getting into Python, so a simple answer would be appreciated, thanks. 我是初学者进入Python,所以一个简单的答案将不胜感激,谢谢。

You generally don't want to have objects that have the same names as your classes. 您通常不希望具有与您的类具有相同名称的对象。 If they're not defined at the same scope, there isn't actually a conflict, but it's still confusing. 如果他们没有在相同的范围内定义,实际上并没有冲突,但它仍然令人困惑。

However, if you follow the typical Python naming conventions, this won't be a problem: your classes start with capital letters, and your variables start with lowercase letters. 但是,如果您遵循典型的Python命名约定,这将不会成为问题:您的类以大写字母开头,而您的变量以小写字母开头。 So, your variable is called screen , and it doesn't matter that you have a class called Screen . 因此,您的变量称为screen ,并且您有一个名为Screen的类并不重要。

Meanwhile, you do probably want to put related classes together into a module. 同时,您可能希望将相关的类放在一个模块中。 Objects of classes defined in your gameObjects module will not have access to variables defined in main, but you don't want them to. gameObjects模块中定义的类的对象将无法访问main中定义的变量,但您不希望它们访问。 Global variables are almost always a bad idea. 全局变量几乎总是一个坏主意。 If an object needs access to a variable, pass that variable into its constructor. 如果对象需要访问变量,请将该变量传递给其构造函数。

Before creating your own large project, you should probably look around a few other large projects to see how they organize things. 在创建自己的大型项目之前,您应该查看其他一些大型项目以了解它们如何组织事物。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM