So I want to iterate through a dictionary and for each key in the dictionary I want to make a class variable but the name of the class variable will not change according to the loop
for example:
fruits= {'pears': 3, 'strawberries': 5, 'apples': 2, 'watermelons': 1, 'oranges':4}
class Fruit():
def __init__(self, fruits):
for fruitname in fruits:
self.fruitname = fruits[fruitname]
#How do I change fruitname when it is "connected" to the self
I tried looking for some other questions on stackoverflow but couldn't really find the problem because I have no idea how I should call this.
CodePudding user response:
If you want to add all the dictionary values as instance attributes, either you can use a setattr
call with name and value, or just update the __dict__
.
For Eg. see below
fruits = {'pears': 3, 'strawberries': 5, 'apples': 2, 'watermelons': 1, 'oranges': 4}
class Fruit():
def __init__(self, fruits):
self.__dict__.update(fruits)
if __name__ == '__main__':
fruit = Fruit(fruits)
print(fruit.pears)
print(fruit.strawberries)
print(fruit.apples)
prints out
3
5
2
CodePudding user response:
That's where setattr () comes in: https://www.w3schools.com/python/ref_func_setattr.asp
Note that there are differences between setattr( self, 'foo', 'bar')
and setattr( Fruit, 'foo', 'bar')
Also note that the python argparse Namespace has been doing that for some time and usually people prefer the dict over the attributes
CodePudding user response:
Use setattr
fruits= {'pears': 3, 'strawberries': 5, 'apples': 2, 'watermellons': 1, 'oranges':4}
class Fruit():
def __init__(self, fruits):
for fruit_name, fruit in fruits.items():
setattr(self, fruit_name, fruit)
fruit_instance = Fruit(fruits)
setattr
and getattr
could be used to respectively get or set attribute on an object. hasattr
could also be used to ask for existance.