0

I'd like to change the attribute of an object that has been assigned as an attribute of another object.

cageNumber = int(input('Cage number: '))
mouseNumber = int(input('Mouse number: '))
mouseID = f'm{mouseNumber}'
setattr(cages[cageNumber].mouseID, 'sacrificed', True)

The cage is an instance of a class and each cage has 5 attributes. Each mouse is an instance of a class and they are assigned as the attributes of the cage object. The cages are contained in a dictionary.

My cage has no attribute named mouseID, but it DOES have 5 attributes named
m1, m2, m3, m4, and m5. These are solved by mouseID = f'm{mouseNumber}'.

I'd like to do something like this: cage[101].m3.sacrificed = True for each of 5 mice
(m1 - m5).

1 Answers1

0

If I understand what you're looking for, you need to use a call to getattr() to get the attribute by name as a string. Also, I don't really see a reason to use setattr() here.

getattr(cages[cageNumber], mouseID).sacrificed = True

Although if you're doing this sort of thing a lot (and even if you're not), it would probably be less cumbersome to put m1, m2, etc. into a list or dict for easier indexing, so you can instead do something like:

cages[cageNumber].mice[mouseID].sacrificed = True
glibdud
  • 7,550
  • 4
  • 27
  • 37