Search code examples
pythonattributeerror

Python3 AttributeError when setting properties using **kwargs


Simply put I do understand why I can't set a property using a for loop with **kwargs like so:

class Person():
    def __init__(self, onevar, *args, **kwargs):
        self.onevar = onevar
        for k in kwargs:
            self.k = kwargs[k]
            print(k, self.k)   

def run():
    ryan = Person('test', 4, 5, 6, name='ryan', age='fifty')
    print(ryan.name)

def main():
    run()

if __name__=="__main__":
    main()

This returns the following:

AttributeError: 'Person' object has no attribute 'name'

Anyone know why?


Solution

  • When you assign self.k you're not actually creating an attribute named the value of k, you're just creating an attribute called k repeatedly. If I understand what you're trying to do, you need to replace

    self.k = kwargs[k]
    

    with

    setattr(self, k, kwargs[k])
    

    to achieve what you want.