Reputation: 21
First of all I'd like to say im a Python beginner (or programming beginner for that matter) and I'm trying to figure out how to print attributes from a object based on user input.
This is the code I have so far:
class Customer:
"De klasse customer"
def __init__(self, naam, adres, woonplaats, email):
self.naam = naam
self.adres = adres
self.woonplaats = woonplaats
self.email = email
input1 = input ("Enter the object name")
print(input1.naam) ## ** << This is what i like to know**
a = Customer('Name1', 'address', 'Utrecht', '[email protected]')
b = Customer('Name2', 'Bonestaak', 'Maarssen', 'Bijjaapishetaltijdraakhotmail.com')
So I basically want this: print(a.naam)
to work, but the 'a' must be entered by a user.
Did some searching but no success so far.
Upvotes: 2
Views: 460
Reputation: 55207
You can use the locals
function:
>>> a = {1:'abc'}
>>> obj = raw_input('Obj?> ')
Obj?> a
>>> print locals()[obj][1]
abc
>>>
This is however an highly insecure construct (there are other things in locals!)
A cleaner way would be to:
customers = {
'a' : Customer('Name1', 'address', 'Utrecht', '[email protected]')
'b' : Customer('Name2', 'Bonestaak', 'Maarssen', 'Bijjaapishetaltijdraakhotmail.com')
}
customer = raw_input('Customer? > ')
print customers[customer].naam
You'll need to handle KeyError
properly though!
Upvotes: 1