class()和class之间有什么区别

时间:2014-05-21 17:57:39

标签: 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_()

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

让我们回顾每种情况下发生的事情。

# 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]

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


这是一个可能的解决方法。

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]