簡體   English   中英

如何解決此Python代碼上的錯誤?

[英]How can I fix the error on this Python code?

我有這個超類:

導入wx

class Plugin(wx.Panel):
    def __init__(self, parent, *args, **kwargs):
        wx.Panel.__init__(self, parent, *args, **kwargs)
        self.colorOver = ((89,89,89))
        self.colorLeave = ((110,110,110))
        self.SetBackgroundColour(self.colorLeave)
        self.SetForegroundColour(self.colorLeave)
        self.name = "plugin"

        wx.StaticText(self, -1, self.getName(), style=wx.ALIGN_LEFT)


        self.Bind(wx.EVT_ENTER_WINDOW, self.onMouseOver)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.onMouseLeave)

    def onMouseOver(self, event):
        self.SetBackgroundColour(self.colorOver)
        self.Refresh()

    def onMouseLeave(self, event):
        self.SetBackgroundColour(self.colorLeave)
        self.Refresh()

    def OnClose(self, event):
        self.Close()
        app.Destroy()

    def getName(self):
        return self.name

和這個子類:

import plugin
import wx

class noisePlugin(plugin.Plugin):
    self.name = "noise"

這給了我編譯子類的錯誤:

Traceback (most recent call last):
  File "C:\Users\André Ferreira\Desktop\Tese\Código Python\SoundLog\Plugins\noisePlugin.py", line 4, in <module>
    class noisePlugin(plugin.Plugin):
  File "C:\Users\André Ferreira\Desktop\Tese\Código Python\SoundLog\Plugins\noisePlugin.py", line 5, in noisePlugin
    self.name = "noise"
NameError: name 'self' is not defined

我該如何解決該錯誤? 我想要getName()方法返回實例化類的名稱!

提前致謝 :)

制作子類

class noisePlugin(plugin.Plugin):
    def __init__(self, *a, **k):
        plugin.Plugin.__init__(self, *a, **k)
        self.name = "noise"

每當您想使用self. 您必須在方法內進行某些操作,而不是在方法外的類級別進行操作!

是什么讓您認為這可行?

class noisePlugin(plugin.Plugin):
    self.name = "noise"

你為什么不復制

class Plugin(wx.Panel):
    def __init__(self, parent, *args, **kwargs):

那是在self.name=嗎?

對於您似乎正在嘗試的模式(名稱與類而不是與實例的關聯更多),這通常是一個更好的習慣用法:

class A(object):
    name = 'parent'

    def __init__(self, ...):
       ... etc

class B(A):
    name = 'child'

    def __init__(self, ...):
        A.__init__(self, ...)
        ... etc

即使name屬性存儲在類而不是實例上,您也可以在所有實例中使用self.name對其進行訪問。 通常,如果您發現自己分配的靜態(不變)屬性在給定類的所有實例中都相同,則應僅使用此類的靜態類屬性。

在一個略有不同的主題上,您是否知道所有wxPython小部件已經具有name屬性,可以在初始化時使用name關鍵字參數來分配該屬性,並可以使用GetName()或(在wxPython的最新版本中)訪問Name屬性? 如果您不分配它,它將默認為一些相當通用的類特定值(例如"textctrl" "text""textctrl" )。 根據您要執行的操作,也許您可​​以僅使用它來代替自己的namegetName() wxPython本身不使用此值,因為它供程序員使用,以供您使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM