Python3 AttributeError while setting properties using ** kwargs
Simply put, I understand why I can't set the property using a loop for
with **kwargs
like this:
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'
Does anyone know why?
+3
source to share
2 answers
EDIT : @ tzaman's answer is better. Use setattr
as he suggests.
You expect to k
become a variable, but that won't work. However, you can expand the base object
in Python and set your variables using an internal property __dict__
.
You can also use iteritems()
to get the value directly.
class Person(object):
def __init__(self, onevar, *args, **kwargs):
self.onevar = onevar
for k,v in kwargs.iteritems():
self.__dict__[k] = v
print(k, self.__dict__.get(k))
0
source to share