class() 和 class 有什么区别

  • 本文关键字:class 区别 python oop
  • 更新时间 :
  • 英文 :


所以我正在试用PySide,一开始我尝试使用:

t = test()

它会给我:TypeError: trybutton() takes 2 positional arguments but 3 were given

但意外的是,我发现如果我这样做的话,它会运行得很好:

t = test

所以我想知道怎么会这样?

class test():
def trybutton(name, self):
    return QPushButton(name, self)
class main(QMainWindow):
        def __init__(self, parent=None):
            super(main, self).__init__(parent)
            self.testui()
        def testui(self):
            main.set_button(self, "test", "testy")
        def set_button(self, *names):
            t = test
            b = [t.trybutton(name, self) for name in names]
if __name__ == "__main__":
        app = QApplication(sys.argv)
        frame = main()
        frame.show()
        app.exec_()

trybutton是一个类方法,不应从实例化对象调用

当一个实例化的对象调用他的一个方法时,它总是将自己作为第一个参数发送所以当你做t=test()然后CCD_ 6该方法本身将接收3个参数(_object、a、b(,从而接收错误takes 2 positional arguments but 3 were given

让我们来看看每种情况下会发生什么。

# Assign the class test to the variable t
t = test
# Call the method on the class, passing in two arguments explicitly.
b = [t.trybutton(name, self) for name in names]

# Create an object of the class test and assign it to the variable t
t = test()
# Call the method on the class, passing in two arguments explicitly, and one argument implicitly
# Note that the implicit argument is the argument t itself, which is passed as the first argument
b = [t.trybutton(name, self) for name in names]

这就是为什么在预期2时传递3参数时会出现错误。


这里有一个可能的解决方案。

class test():
   def trybutton(self, name):
        return QPushButton(name, self)
t = test()
# pass one argument explicitly, one implicitly.
b = [t.trybutton(name) for name in names]

最新更新