Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 460
Startec Avatar asked Feb 02 '26 14:02

Startec


1 Answers

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.

like image 200
tzaman Avatar answered Feb 05 '26 07:02

tzaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!