Python Forum
# of Positional arguments to pass for creating an object? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: # of Positional arguments to pass for creating an object? (/thread-4794.html)



# of Positional arguments to pass for creating an object? - burvil - Sep-09-2017

I'm getting an error when trying to instantiate a class, where I pass two arguments, and the third one (for self) is implicit. When I only pass in one variable (hostname), it runs, but doesn't pass in the data to assign to the attributes as it should.

The code:
#!/usr/local/bin/python3.4

import re, requests, sys, json, time, logging, os, platform, pprint

###################################################
# Class Asset
class Asset(object):
    def __init__(self, hostname, **kwargs):
        #log.debug("hostname is " + hostname + ", kwargs is " + str(kwargs))
        setattr(self, "hostname", hostname)
        for key in kwargs:
            setattr(self, key, kwargs[key])
    def get(key):
        return self.key

    def dump(self):
        for attr in dir(obj):
            if hasattr( obj, attr ):
                print( "obj.%s = %s" % (attr, getattr(obj, attr)))

data = dict()
hostname = "this-host"
data["test1"] = "val1"
data["test2"] = "val2"
test_obj = Asset(hostname, data)
The result when running it:
$ ./test3.py
Traceback (most recent call last):
  File "./test3.py", line 25, in <module>
    test_obj = Asset(hostname, data)
TypeError: __init__() takes 2 positional arguments but 3 were given
Any thoughts on why I'm getting this error?


RE: # of Positional arguments to pass for creating an object? - kalyanben - Sep-09-2017

second argument which you are giving should be keyword argument. that is the error. you are giving it as non keyword argument


RE: # of Positional arguments to pass for creating an object? - burvil - Sep-09-2017

Thanks. I double checked my reference; I was using https://stackoverflow.com/questions/2466191/set-attributes-from-dictionary-in-python as a model. I matched the syntax, and it works now.