如何使用变量作为对象名从对象获取属性

时间:2015-06-11 20:34:13

标签: python python-3.x

我想要做的是随机选择列表中的项目,然后使用它来完成该对象的属性。我显然可以对current_target变量(例如Creature.Dog.attr1)进行硬编码,但理想情况下我希望生成它。

我的代码是这样的:

class Creature(object):

    def __init__(self, name, attr1, attr2):
        self.name = name
        self.attr1 = attr1
        self.attr2 = attr2


Squirrel = Creature("Squirrel", 20, 1)
Dog = Creature("Dog", 50, 10)
Goblin = Creature("Goblin", 100, 100)

creature_list = ['Squirrel', 'Dog', 'Goblin']

def get_creature():
    return random.choice(creature_list)

这些是从我的主要课程中调用的:

current_target = Creature.get_creature()
print("The current target is %s, and has %s, and %s"  
     % (current_target, Creature.current_target.attr1, Creature.current_target.attr2))

2 个答案:

答案 0 :(得分:1)

使用实例而不是字符串

一个简单的更改是将您的Creature个实例放在列表中并从中进行选择。

import random

class Creature(object):

    def __init__(self, name, attr1, attr2):
        self.name = name
        self.attr1 = attr1
        self.attr2 = attr2


Squirrel = Creature("Squirrel", 20, 1)
Dog = Creature("Dog", 50, 10)
Goblin = Creature("Goblin", 100, 100)

creature_list = [Squirrel, Dog, Goblin]

def get_creature():
    return random.choice(creature_list)

current_target = get_creature()
print("The current target is %s, and has %s, and %s"
     % (current_target.name, current_target.attr1, current_target.attr2))

答案 1 :(得分:1)

class Creature(object):

    def __init__(self, name, attr1, attr2):
        self.name = name
        self.attr1 = attr1
        self.attr2 = attr2

Squirrel = Creature("Squirrel", 20, 1)
Dog = Creature("Dog", 50, 10)
Goblin = Creature("Goblin", 100, 100)

creature_list = [Squirrel, Dog, Goblin]

def get_creature():
    return random.choice(creature_list)
current_target = get_creature()
print("The current target is %s, and has %s, and %s"
 % (current_target.name, current_target.attr1, current_target.attr2))