简体   繁体   English

.PY文件中有多少个类

[英]how many classes in a .PY file

I'm learning Python and WxPython . 我正在学习PythonWxPython So far, I'm following the examples in AnotherTutorial , which is mainly wxPython related. 到目前为止,我正在关注AnotherTutorial中的示例,该示例主要与wxPython相关。
I'm trying to understand the following code: 我试图理解以下代码:

import wx

class MyMenu(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(380, 250))

        menubar = wx.MenuBar()
        file = wx.Menu()
        edit = wx.Menu()
        help = wx.Menu()
        file.Append(101, '&Open', 'Open a new document')
        file.Append(102, '&Save', 'Save the document')
        file.AppendSeparator()
        quit = wx.MenuItem(file, 105, '&Quit\tCtrl+Q', 'Quit the Application')
        quit.SetBitmap(wx.Image('stock_exit-16.png',wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        file.AppendItem(quit)
        edit.Append(201, 'check item1', '', wx.ITEM_CHECK)
        edit.Append(202, 'check item2', kind=wx.ITEM_CHECK)
        submenu = wx.Menu()
        submenu.Append(301, 'radio item1', kind=wx.ITEM_RADIO)
        submenu.Append(302, 'radio item2', kind=wx.ITEM_RADIO)
        submenu.Append(303, 'radio item3', kind=wx.ITEM_RADIO)
        edit.AppendMenu(203, 'submenu', submenu)
        menubar.Append(file, '&File')
        menubar.Append(edit, '&Edit')
        menubar.Append(help, '&Help')
        self.SetMenuBar(menubar)
        self.Centre()
        self.Bind(wx.EVT_MENU, self.OnQuit, id=105)

    def OnQuit(self, event):
        self.Close()

class MyApp(wx.App):
    def OnInit(self):
        frame = MyMenu(None, -1, 'menu2.py')
        frame.Show(True)
        return True

app = MyApp(0)
app.MainLoop()

It's mainly line 38 onwards that confuses me, as it defines another class MyApp. 从第38行开始,这使我感到困惑,因为它定义了另一个类MyApp。 Should this not be a separate .PY module of type CLASS which then instantiates the MyMenu class? 这是否不是CLASS类型的单独的.PY模块,然后该模块实例化MyMenu类? I'm using Eclipse, typed the entire code as is and tired to run it but got the error messages 我正在使用Eclipse,按原样键入整个代码,并且厌倦了运行它,但收到了错误消息

Traceback (most recent call last):
File "C:\ws2\sample2\simple_gui\menu2.py", line 54, in <module>
    app = MyApp(0)
File "C:\Python27\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 7981, in __init__
    self._BootstrapApp()
File "C:\Python27\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 7555, in _BootstrapApp
    return _core_.PyApp__BootstrapApp(*args, **kwargs)
File "C:\ws2\sample2\simple_gui\menu2.py", line 50, in OnInit
    frame = MyMenu(None, -1, 'menu2.py')
File "C:\ws2\sample2\simple_gui\menu2.py", line 36, in __init__
    menubar.Append(menu_file,'&Edit')
File "C:\Python27\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 11320, in Append
    return _core_.MenuBar_Append(*args, **kwargs)
wx._core.PyAssertionError: C++ assertion "!m_menuBar" failed at ..\..\src\common\menucmn.cpp(820) in wxMenuBase::Attach(): attaching menu twice?

Can anyone shed some light as to why there would be 2 classes in the same py module? 谁能阐明为什么在同一个py模块中会有2个类? (note i'm a noob so assume entry level knowledge of OOP). (请注意,我是一个菜鸟,所以假设您具备OOP入门级知识)。 I got it working on my machine. 我在机器上工作了。 But I'm really trying to understand what the code is doing, especially the app=MyApp(0) line. 但是我真的想了解代码在做什么,尤其是app = MyApp(0)行。 What does this do? 这是做什么的? what is the Zero for, why not another number like 3, or text like "hello". 零的含义是什么,为什么不是另一个数字(如3)或文本(如“ hello”)呢?

If you're used to Java, you know you can only have one public class per file, and it should have the same name as the file itself (sorry if this has changed; it was true when I used Java ;). 如果您习惯使用Java,则知道每个文件只能有一个公共类,并且它的名称应与文件本身相同(对不起,如果更改了,我使用Java时确实如此;)。 This is so when javac is compiling your program it can find dependent but not-yet-compiled classes in other files. 因此,当javac编译程序时,它可以在其他文件中找到相关但尚未编译的类。

Python actually does something very similar -- you have one module per file, and that module has the same name as the file. Python实际上做了非常相似的事情-每个文件有一个模块 ,而该模块与文件具有相同的名称。 You don't notice because you don't explicitly declare the module, but if you do 您没有注意到,因为您没有显式声明模块,但是如果这样做

foo.py : foo.py

class A:
    pass

bar.py : bar.py

import foo
print(foo.A())

you can see that foo has automatically become a module. 您会看到foo已自动成为模块。

So it's almost the same thing, just Python is not as class-centric as Java, so it uses a module as the main unit to break up files. 因此几乎是同一回事,只是Python不像Java那样以类为中心,因此它使用模块作为主要单元来分解文件。

So to answer your question, yes, it's perfectly OK to have as many classes as you want in one file, because they're all in the same module. 因此,要回答您的问题,是的,在一个文件中拥有任意多个类是完全可以的,因为它们都在同一个模块中。

Having one (Frame or Panel) class per file is typical of wxPython coding. wxPython编码通常每个文件有一个(框架或面板)类。 Normally you build your frame without giving any special functionality and then you subclass it for that in another module. 通常,您在构建框架时不提供任何特殊功能,然后在另一个模块中为其子类化。 This way, especially when you work with gui buiding tools like wxGlade, you can modify the gui or even add new widgets to it independly of the code. 这样,尤其是在使用wxGlade等gui生成工具时,您可以修改gui甚至可以独立于代码向其添加新的小部件。

The second App class in your file is also typical of wxPython where it is very common to enclose the application details separated. 文件中的第二个App类也是wxPython的典型特征,其中很常见的是将应用程序详细信息分隔开来。

That said, in Python you can have as many clases per module as you want. 就是说,在Python中,每个模块可以包含任意多个clase。 Wether you have 1 or 5 depends on the functional completness of the module and how functionaly related are those classes. 您是否拥有1或5,取决于模块的功能完备性以及这些类的功能相关性。

In any case, when the module grows to more than 500-1000 lines it could be a good idea to split its contents in different files. 无论如何,当模块增长到500-1000行以上时,最好将其内容拆分到不同的文件中。

Finally, as commented above your code works perfect for me in win7 64-bits with wxpython 2.8. 最后,如上所述,您的代码在wxpython 2.8的win7 64位环境中对我来说非常理想。 (I just had to comment the Set Bitmap line because I had not that image) (我只需要注释“设置位图”行,因为我没有该图像)

Edit: You are right. 编辑:你是对的。 When you instantiate the Application object, the MyMenu frame is created and then the application enters its MainLoop. 实例化Application对象时,将创建MyMenu框架,然后应用程序进入其MainLoop。 The App(value) is used to direct the application output to some places: App(value)用于将应用程序输出定向到某些地方:

App(0) <-> App(False) <-> App(redirect=False)  -> output to shell (i.e stderr, stdout)
App(1) <-> App(True) <-> App(redirect=True)    -> output to an application Frame

With App(1) if you set the parameter filename then you will sent the output to a file. 如果使用App(1)设置参数文件名,则将输出发送到文件。
From wx.App.__doc__ : wx.App.__doc__

param redirect: Should sys.stdout and sys.stderr be redirected? 参数重定向:是否应该重定向sys.stdoutsys.stderr Defaults to True on Windows and Mac, False otherwise. 在Windows和Mac上默认为True,否则为False。 If filename is None then output will be redirected to a window that pops up as needed. 如果filename为None,则输出将被重定向到根据需要弹出的窗口。 (You can control what kind of window is created for the output by resetting the class variable outputWindowClass to a class of your choosing.) (您可以通过将类变量outputWindowClass重置为您选择的类来控制为输出创建哪种窗口。)

The signature of wx.App: wx.App的签名:

wx.App(redirect=True, filename=None, useBestVisual=False, clearSigInt=True)

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

相关问题 如何列出特定.py 文件中的所有类和方法/函数? - How to list all classes and methods/functions in a specific .py file? 如何将 python py 文件中的所有类导入另一个 py 文件中的另一个 class? - how can I import ALL classes in a python py file to another class in another py file? 如何在一个python文件中从多个类中导入一个类 - How to import one class from many classes on one python file 如何跨文件结构导入类和文件; __init__.py 混乱[暂停] - How to Import Classes and Files across file structure; __init__.py confusion [on hold] 如何在__main__中创建一个可以由同一文件中定义的web.py类使用的变量? - How can I create a variable in __main__ that can be used by web.py classes defined in the same file? 如何导入在 __init__.py 中定义的类 - How to import classes defined in __init__.py 如何运行从 Github 下载的 python 项目(有很多带有 .py 的文件)? - How can I run a python project (has many file with .py) which downloaded from Github? Discord.py 没有显示它在多少台服务器中 - Discord.py Not showing how many servers it is in 如何在web2py中生成多对多关系表? - how to generate a many-to-many-relationship FORM in web2py? 限制 .py 文件中的哪些类可以从其他地方导入 - Limit which classes in a .py file are importable from elsewhere
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM