I'm just starting to learn how to code, so please warn me if you see anything wrong here.
I have a class:
class Wii:
def __init__(self, color, gamecube_comp, miinum, installed_games):
self.color = color
self.gamecube_comp = gamecube_comp
self.miinum = miinum
self.installed_games = installed_games
And I want to be able to print attributes from this class based on an external dictionary and some input, so I tried this:
selections = {
"1": Wii_1,
"2": Wii_2,
"color": color,
"gamecube_comp": gamecube_comp,
"miinum": miinum,
"installed_games": installed_games
}
selected_wii = input("Select a Wii from the list (just the number)\n")
selected_att = input("State what you want to know about the selected Wii\n")
print(selections[selected_wii].selections[selected_att])
But it doesn't let me print, because selections
isn't defined inside the class. Is there a way to make it be able to read selections[selected_att]
even if it's not inside the class?
CodePudding user response:
If you have the attribute name as text (a string), the recomended way to retrieve it from an existing instance is using the getattr
built-in:
print(getattr(selections[selected_wii], selected_att))
It is choice of the Python language that attribute names are hard-coded in the source code are distinct from key names, where keys are arbitrary data to retrieve corresponding mapped values. This is in contrast with Javascript, for example, where both are interchangeable.
But then, in contrast with static typed languages where it is either impossible, or very difficult to retrieve an attribute or field named in the source code given its name as data at runtime, Python offers easy to use introspection capabilities that allow that, like the. getattr
call. So, when your design calls for this kind of usage, you are free to do it.