Search code examples
pythonpython-3.xconstructor

__init__() missing 1 required positional argument


I am trying to learn Python. This is a really simple code. All I am trying to do here is to call a class's constructor, initialize some variables there and print that variable, but it is giving me an error, missing 1 required positional argument.

class DHT:
    def __init__(self, data):
        self.data['one'] = '1'
        self.data['two'] = '2'
        self.data['three'] = '3'
    def showData(self):
        print(self.data)
        
if __name__ == '__main__':
    DHT().showData()

Solution

  • You're receiving this error because you did not pass a data variable to the DHT constructor.

    aIKid's and Alexander's answers are nice but won't work because you still have to initialize self.data in the class constructor like this:

    class DHT:
        def __init__(self, data=None):
            self.data = data if data is not None else {}
            self.data['one'] = '1'
            self.data['two'] = '2'
            self.data['three'] = '3'
    
        def showData(self):
            print(self.data)
    

    And then calling the method showData like this:

    DHT().showData()
    

    Or like this:

    DHT({'six':6,'seven':'7'}).showData()
    

    or like this:

    # Build the class first
    dht = DHT({'six':6,'seven':'7'})
    # The call whatever method you want (In our case only 1 method available)
    dht.showData()