简体   繁体   中英

Printing object attributes based on user input in Python 3x

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', 'Email1@hotmail.com')
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.

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', 'Email1@hotmail.com')
    'b' : Customer('Name2', 'Bonestaak', 'Maarssen', 'Bijjaapishetaltijdraakhotmail.com')
}

customer = raw_input('Customer? > ')
print customers[customer].naam

You'll need to handle KeyError properly though!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM