Is there a way to access attributes of a class dynamically in python?

Viewed 66

I am wondering if there is a better way to do what I did in the method addMoneyToCategory. I want to be able to have the name of the attribute as a parameter for the method and then add an integer to that attribute.

class Budget:
    def __init__(self, food = 0, clothing = 0, entertainment = 0):
        self.Food = food
        self.Clothing = clothing
        self.Entertainment = entertainment
        
    def addMoneyToCategory(self, category, amount):
        if category == "Food" or category == "food":
            self.Food += amount
        if category == "Clothing" or category == "clothing":
            self.Clothing += amount
        if category == "Entertainment" or category == "entertainment":
            self.Entertainment += amount

i1 = Budget()
i1.addMoneyToCategory("Food", 20)
3 Answers

You can use getattr to access an attribute and setattr to set an attribute. For example:

    def addMoneyToCategory(self, category, amount):
        settatr(self, category, getattr(self, category) + amount)

You can use str.capitalize to ensure that the category has the uppercased name:

    def addMoneyToCategory(self, category, amount):
        category = category.capitalize()
        settatr(self, category, getattr(self, category) + amount)

This works:

Using builtin dataclasses module.

from dataclasses import dataclass


@dataclass
class Budget:
    Food: int = 0
    Clothing: int = 0
    Entertainment: int = 0

    def addMoneyToCategory(self, category: str, amount: int):
        attr = category.title()
        fv = getattr(self, attr)
        setattr(self, attr, fv + amount)

Usage:

i1 = Budget(Clothing=10)
i1.addMoneyToCategory("Food", 20)
i1.addMoneyToCategory('entertainment', 50)

print(i1)

Result:

Budget(Food=20, Clothing=10, Entertainment=50)

You could use as a very easy way dataclasses, they where contribute in Python 3.7. This could look like (It has not the Function you wanted, but the result is similar):

from dataclasses import dataclass


@dataclass
class Budget:
    Food: int = 0
    Clothing: int = 0
    Entertainment: int = 0

    
i1 = Budget()
i1.Food += 20
Related