TypeError: Missing 1 required positional argument: 'self'

后端 未结 6 818
借酒劲吻你
借酒劲吻你 2020-11-22 02:18

I am new to python and have hit a wall. I followed several tutorials but cant get past the error:

Traceback (most recent call last):
  File \"C:\\Users\\Dom\         


        
相关标签:
6条回答
  • 2020-11-22 02:55

    Works and is simpler than every other solution I see here :

    Pump().getPumps()
    

    This is great if you don't need to reuse a class instance. Tested on Python 3.7.3.

    0 讨论(0)
  • 2020-11-22 02:56

    You need to instantiate a class instance here.

    Use

    p = Pump()
    p.getPumps()
    

    Small example -

    >>> class TestClass:
            def __init__(self):
                print("in init")
            def testFunc(self):
                print("in Test Func")
    
    
    >>> testInstance = TestClass()
    in init
    >>> testInstance.testFunc()
    in Test Func
    
    0 讨论(0)
  • 2020-11-22 02:59

    The self keyword in Python is analogous to this keyword in C++ / Java / C#.

    In Python 2 it is done implicitly by the compiler (yes Python does compilation internally). It's just that in Python 3 you need to mention it explicitly in the constructor and member functions. example:

     class Pump():
     //member variable
     account_holder
     balance_amount
    
       // constructor
       def __init__(self,ah,bal):
       |    self.account_holder = ah
       |    self.balance_amount = bal
    
       def getPumps(self):
       |    print("The details of your account are:"+self.account_number + self.balance_amount)
    
     //object = class(*passing values to constructor*)
     p = Pump("Tahir",12000)
     p.getPumps()
    
    0 讨论(0)
  • 2020-11-22 03:03

    You can call the method like pump.getPumps(). By adding @classmethod decorator on the method. A class method receives the class as the implicit first argument, just like an instance method receives the instance.

    class Pump:
    
    def __init__(self):
        print ("init") # never prints
    
    @classmethod
    def getPumps(cls):
                # Open database connection
                # some stuff here that never gets executed because of error
    

    So, simply call Pump.getPumps() .

    In java, it is termed as static method.

    0 讨论(0)
  • 2020-11-22 03:11

    You need to initialize it first:

    p = Pump().getPumps()
    
    0 讨论(0)
  • 2020-11-22 03:13

    You can also get this error by prematurely taking PyCharm's advice to annotate a method @staticmethod. Remove the annotation.

    0 讨论(0)
提交回复
热议问题