2

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.

2
  • This class docstring does not provide any new information; please don't bother to add one unless it actually has a use :) Commented Nov 15, 2012 at 0:37
  • Anyway, that is wrong thinking about the problem; your customer already has a name (the naam attribute), and variable names are supposed to be under your control. Think about it: if you leave it up to the user to name your variable, then how do you expect to know what name to use, so you can check what is in the variable and use it? You are writing the code before the user gives you a name... Commented Nov 15, 2012 at 0:38

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.