Iron Python基于字符串输入获取类实例的属性

时间:2014-07-06 10:06:07

标签: python ironpython instances

这是我的代码,我是python的新手,无法理解为什么这不起作用,我希望能够在用户选择特定实例后打印类实例属性。我不确定这是否可能,但如果有一些帮助将非常感激。

class Animal(object):
    def __init__(self, name, age, happiness, hunger):
        self.name = name
        self.age = age
        self.happiness = happiness
        self.hunger = hunger


def animal_print(animal):
    if animal.lower() in animals:
        print "%s, the %s, is %s years old. % (animal.name, animal, animal.age)


pig = Animal("Joe", 12, 7, 6)
fox = Animal("Fred", 4, 4, 6),
cow = Animal("Bessy", 9, 6, 3),
horse = Animal("Sally", 7, 8, 8),

animals = ["pig", "fox", "cow", "horse"]


animal_print(raw_input("Which animal would you like to see: "))

此代码的基础是用户将从动物列表中输入动物,然后我希望它返回成员属性。如果我将我的代码更改为下面的代码它可以工作,但理想情况下我只想为所有类实例创建一个print语句,而下面的代码需要为每个实例创建一个单独的print语句:

def animal_print(animal):
    if animal.lower() in animals:
        print "%s, the %s, is %s years old % (pig.name, animal, pig.age)

2 个答案:

答案 0 :(得分:0)

str 'pig'Animal的实例不同,存储在变量pig中。

raw_input返回str。因此,在animal_print函数中,animalstrstr没有name属性,因此animal.name会引发AttributeError

至少有三种方法可以修复代码:使用“白名单”字典,在globals()字典中查找值,或使用eval。在这三个中,使用白名单是最安全的,因为不应该在任意用户输入上允许全局查找和eval。一个人可以泄露私人信息,另一个可能允许恶意用户运行任意代码。

所以使用白名单:

animap = {'pig': pig,
          'fox': fox}
anistr = raw_input(...)   # str
animal = animap[anistr]   # Animal instance

class Animal(object):
    def __init__(self, name, age, happiness, hunger):
        self.name = name
        self.age = age
        self.happiness = happiness
        self.hunger = hunger


def animal_print(anistr):
    animal = animap.get(anistr.lower())
    if animal is not None:
        print "%s, the %s, is %s years old." % (animal.name, anistr, animal.age)


pig = Animal("Joe", 12, 7, 6)
fox = Animal("Fred", 4, 4, 6)
cow = Animal("Bessy", 9, 6, 3)
horse = Animal("Sally", 7, 8, 8)

animap = {'pig': pig,
          'fox': fox,
          'cow': cow,
          'horse': horse}

anistr = raw_input("Which animal would you like to see: ")

animal_print(anistr)

答案 1 :(得分:0)

最好使用字典作为动物实例的容器。键可以是动物名称作为字符串,值可以是Animal实例。然后你的animal_print()函数只能处理打印动物属性。

def animal_print(animal):
    print "%s, the %s, is %s years old." % (animal.name, animal, animal.age)

animals = {
    'pig': Animal("Joe", 12, 7, 6),
    'fox': Animal("Fred", 4, 4, 6),
    'cow': Animal("Bessy", 9, 6, 3),
    'horse': Animal("Sally", 7, 8, 8),
}

user_animal = raw_input("Which animal would you like to see: ")
try:
    animal_print(animals[user_animal.lower()])
except KeyError:
    print "I no nothing about animal %s." % user_animal