class method with no arguments produces TypeError

后端 未结 3 1256
后悔当初
后悔当初 2021-01-01 02:40

This code:

class testclass:
    def __init__(self,x,y):
        self.x = x
        self.y = y
        self.test()

    def test():
        print(\'test\')

i         


        
3条回答
  •  [愿得一人]
    2021-01-01 02:42

    Python always passes the instance as the first argument of instance methods, this means that sometimes the error messages concerning the number of arguments seems to be off by one.

    class testclass:
        def __init__(self,x,y):
            self.x = x
            self.y = y
            self.test()
    
        def test(self):          ## instance method
            print('test', self)
    
    if __name__ == '__main__':
        x = testclass(2,3)
    

    If you don't need access to the class or the instance, you can use a staticmethod as shown below

    class testclass:
        def __init__(self,x,y):
            self.x = x
            self.y = y
            self.test()
    
        @staticmethod
        def test():
            print('test')
    
    if __name__ == '__main__':
        x = testclass(2,3)
    

    A classmethod is similar, if you need access to the class, but not the instance

    class testclass:
        def __init__(self,x,y):
            self.x = x
            self.y = y
            self.test()
    
        @classmethod
        def test(cls):
            print('test', cls)
    
    if __name__ == '__main__':
        x = testclass(2,3)
    

提交回复
热议问题