In Python 2, the following would work as I believe you intend:
class Fruit(object):
def __init__(self, name, color, size):
self.name = name
self.color = color
self.size = size
Apple = Fruit('Apple', 'red', 'small')
fruit_class = input('Choose type of fruit: ')
print(fruit_class.color)
However, the function input
in Python 3 behaves like raw_input
does in Python 2. The is no function in Python 3 like Python 2's input
. However, effectively the same functionality can be achieved using eval(input())
in Python 3 as described in this post.
The code would look like this:
Apple = Fruit('Apple', 'red', 'small')
fruit_class = eval(input('Choose type of fruit: '))
print(fruit_class.color)
However, use of eval
is dangerous as the user can execute arbitrary code against the system. A mapping between the input string values you expect and the user to input and the class instances to which they should map could serve the same use case. For example:
Apple = Fruit('Apple', 'red', 'small')
fruits = {
'Apple': Apple,
}
fruit_class_type = input('Choose type of fruit: ')
print(fruits[fruit_class_type].color)