向类中的类添加方法

2024-09-29 04:28:50 发布

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

完全是脑子放屁,连我问的问题都不确定。如何添加/更改类中存在的类的方法?你知道吗

我正在构建一个用QtDesigner设计的QT GUI。我的Python程序导入一个新类并将其子类化为GUI文件类。我想将一个方法更改为该类中的按钮。你知道吗

基本上我有下面的内容,我想给'aButton'添加一个方法。你知道吗

qtDesignerFile.py文件

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        self.aButton = QtGui.QPushButton()

myPythonFile.py文件

import qtDesignerFile

class slidingAppView(QMainWindow,slidingGuiUi.Ui_MainWindow):
    def __init__(self,parent=None):
        super(slidingAppView,self).__init__(parent)

Tags: 文件方法pyselfuiinitdefgui
2条回答
self.aButton.PrintHello = lambda : print "hello!"

或者

def aMethod():
    do_something()

self.aButton.DoSomething = aMethod 

两种方法都可以。。。可能还有更多的方法。。。这假设aButton是从对象继承的python类

为了补充Joran的答案,方法如下:

def foo():
    pass

instance.foo = foo

将像静态方法一样工作(它们不会将实例作为第一个参数传递)。如果要添加绑定方法,可以执行以下操作:

from types import MethodType

def foo(instance):
    # this function will receive the instance as first argument
    # similar to a bound method
    pass

instance.foo = MethodType(foo, instance, instance.__class__)

相关问题 更多 >