Accessing a class instance's attributes using user input

故事扮演 提交于 2019-12-12 01:59:55

问题


So I have this code:

class vehicle(object):
    def __init__(self):
        self.age = 6
        self.make = 8
        self.colour = 'colour'
        self.cost = 'cost'

class car(vehicle):
    def __init__(self):
        vehicle.__init__(self)
        self.type = 'car'

car1 = car()
print car1.make, car1.colour, car1.cost, car1.type, car1.age

n = raw_input()
dic = {'name' : n}
dic['name'] = car()
print dic['name'].make

In the last bit, I was able to resolve a previous issue I had: Creating an instance of the car class with its name being one that the user inputs in n

Now, say I wanna ask the user to input a name and now I have to find the class' instance that has that name.

For example if at one point an instance with the name car2 was created. Now user wants to get info about car2 and inputs 'car2'. how can I use this input to access attributes of the instance called car2?

I tried:

a = raw_input()
dic['fetch'] = a
dic['fetch'].make

does not work.


回答1:


It seems to me you have a fair bit of misunderstanding. The way you're assigning the input into the dictionary doesn't make sense. Your description indicates that you want a dictionary that maps a "name" to a car description.

Your initial creation of the dictionary is off. The way you're currently doing it, you're actually losing the name the user inputs when you assign the car data. Some better variable naming might help you. Create your dictionary like this:

cars_by_name = dict()
name = raw_input()
cars_by_name[name] = car()

So now you have a name (given by the user) that maps to a car description.

Now you need to fetch that same car instance again. You do it by using the name as the key in the dictionary:

name2 = raw_input()
print cars_by_name[name2].make

Next, let's look at your classes. My first question: why do you need a vehicle and a car class? If you're never going to have classes other than car inheriting from vehicle, you don't really need them both. Even if you do plan the have more subclasses, I would probably still recommend against inheritance here. Your vehicle has no behavior (methods) for subclasses to inherit. It's just a data object. With duck typing so strongly encouraged in Python, inheriting from a class with no methods doesn't buy you anything. (What a base class would buy you with methods is that you'd only have to define the method in one place, making it easier to modify later on.) Particularly in your case, there doesn't seem to be any motivation to create a subclass at all. A single class for all vehicles will work just fine. So let's simplify your classes:

class Vehicle(object):
    def __init__(self):
        self.age = 6
        self.make = 8
        self.colour = 'colour'
        self.cost = 'cost'
        self.type = 'car'

(Also, note that class names are usually given in camel case in Python.) Now there's one more problem here: those constants. Not all Vehicles are going to have those same values; in fact, most won't. So lets make them arguments to the initializer:

class Vehicle(object):
    def __init__(self, age, make, colour, cost, type):
        self.age = age
        self.make = make
        self.colour = colour
        self.cost = cost
        self.type = type

Then you create one like this:

v = Vehicle(6, 8, 'colour', 'cost', 'car')

Good luck in your endeavors learning. Hope this helps.




回答2:


If I understand you correctly and you want to map string names to instances:

n = raw_input()
dic = {n: car()}
print dic[n].make
print(dic)
dic[n].cost = 10000
print(dic[n].cost)

Another option would be to take a name for each car instance and have a class attribute dict mapping names to self.

In [13]: paste
class vehicle(object):
    def __init__(self):
        self.age = 6
        self.make = 8
        self.colour = 'colour'
        self.cost = 'cost'

class car(vehicle):
    dic = {}
    def __init__(self, name):
        vehicle.__init__(self)
        car.dic = {name: self}
        self.type = 'car'
        self.name=name

car1 = car("car1")
car2 = car("car2")
car2.colour="blue"
print car1.make, car1.colour, car1.cost, car1.type, car1.age

n = raw_input()
print car.dic[n]
print car.dic[n].make
print car.dic[n].colour

## -- End pasted text --
8 colour cost car 6
car2
<__main__.car object at 0x7f823cd34490>
8
blue


来源:https://stackoverflow.com/questions/27891979/accessing-a-class-instances-attributes-using-user-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!