Python Forum

Full Version: # of Positional arguments to pass for creating an object?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
second argument which you are giving should be keyword argument. that is the error. you are giving it as non keyword argument
Thanks. I double checked my reference; I was using https://stackoverflow.com/questions/2466...-in-python as a model. I matched the syntax, and it works now.