简体   繁体   English

使用函数变量调用类实例时,Python的“ str”对象没有属性“名称”

[英]Python 'str' object has no attribute 'name' when using a function variable to call a class instance

I'm just starting to learn programming with python. 我刚刚开始学习使用python编程。 I'm trying to make a game similar to Pokemon, and I'm trying to apply OOP into agame. 我正在尝试制作类似于《口袋妖怪》的游戏,并且试图在游戏中应用OOP。

I started by making a Pokemon class, and adding class-defined attributes such as name, HP, etype, attacks. 首先,制作一个Pokemon类,并添加类定义的属性,例如名称,HP,etype,攻击。 "attacks" is a dictionary of lists. “攻击”是列表的字典。

My problem now is I'm trying to develop a simple battle engine where I can switch out pokemons. 我现在的问题是,我正在尝试开发一个简单的战斗引擎,在这里我可以换掉口袋妖怪。 For this reason, I made a function/method name fight(). 因此,我将函数/方法命名为fight()。

Inside that I have a variable named current_pokemon.name so whenever I switch out the pokemon, I can use the new pokemon's name, attacks, etc. 在其中,我有一个名为current_pokemon.name的变量,因此每当切换出神奇宝贝时,我都可以使用新的神奇宝贝的名称,攻击等。

I used raw_input to return a string that replaces current_pokemon, which has a .name attribute to call on a pikachu instance. 我使用了raw_input返回一个替换current_pokemon的字符串,该字符串具有一个在皮卡丘实例上调用的.name属性。 Instead, I get the 'str' object has no attribute. 相反,我得到的'str'对象没有属性。 Why doesn't this work? 为什么不起作用? It worked outside the function fight() when I explicitly wrote pikachu.attribute. 当我显式编写pikachu.attribute时,它在功能fight()之外起作用。

class Pokemon(object):
    def __init__(self, name, HP, etype, attacks):
        self.name = name
        self.HP = HP
        self.etype = etype
        self.attacks = attacks #2 attacks with name, dmg, type and power points

geodude = Pokemon("Geodude", 100, "Ground", 
                  attacks = 
                  {"Tackle":["Tackle",30,"Normal","35"], 
                   "Rollout":["Rollout",50,"Rock","20"]
                  })
                    #attacks = {attack:[attack_name, dmg, type, PP]}

pikachu = Pokemon("Pikachu", 100, "Lightning", 
                  attacks = 
                  {"Thunder Shock":["Thunder Shock",40,"Electric"],
                   "Quick Attack":["Quick Attack",40,"Normal"]
                  })

#selects pikachu's attack
print "Pokemon's name is", (pikachu.name)
print "Pikachu's %s attack damages %d" % ((pikachu.attacks["Thunder Shock"][0]),(pikachu.attacks["Thunder Shock"][1]))

pikachu.HP = pikachu.HP - geodude.attacks["Rollout"][1]
print "Pikachu's HP is", (pikachu.HP)
pikachu.HP = pikachu.HP - geodude.attacks["Tackle"][1]
print "Pikachu's HP is", (pikachu.HP)

#Pokemon Battle test with stored variable
#Value selector - replace all var attributes using an easy function
#Use Solution 2

def fight():
    current_pokemon = raw_input("pikachu or geodude? > ")
    print current_pokemon.name
    print current_pokemon.attacks


fight()

Output: 输出:

Pokemon's name is Pikachu
Pikachu's Thunder Shock attack damages 40
Pikachu's HP is 50
Pikachu's HP is 20
pikachu or geodude? > pikachu
Traceback (most recent call last):
  File "poke_game_stack.py", line 40, in <module>
    fight()
  File "poke_game_stack.py", line 36, in fight
    print current_pokemon.name
AttributeError: 'str' object has no attribute 'name'

Please help noob me with this simple problem! 请帮助菜鸟这个简单的问题! Thanks! 谢谢!

raw_input() always returns a string; raw_input()总是返回一个字符串; it will not return an object you stored by the same name. 它不会返回您使用相同名称存储的对象。

Store your pokemons in a dictionary, (mapping string to object) then use the string from raw_input() to map to one of those objects: 将您的神奇宝贝存储在字典中(将字符串映射到对象),然后使用raw_input()的字符串映射到这些对象之一:

pokemons = {
    'geodude': Pokemon("Geodude", 100, "Ground", 
                  attacks = 
                  {"Tackle":["Tackle",30,"Normal","35"], 
                   "Rollout":["Rollout",50,"Rock","20"]
                  }),

    'pikachu': Pokemon("Pikachu", 100, "Lightning", 
                  attacks = 
                  {"Thunder Shock":["Thunder Shock",40,"Electric"],
                   "Quick Attack":["Quick Attack",40,"Normal"]
                  }),
}

def fight():
    current_pokemon_name = raw_input("pikachu or geodude? > ")
    current_pokemon = pokemons[current_pokemon_name]
    print current_pokemon.name
    print current_pokemon.attacks
current_pokemon = raw_input("pikachu or geodude? > ")
print current_pokemon.name
print current_pokemon.attacks

The raw_input() method returns a str , and strings have no property such as name or attacks . raw_input()方法返回一个str ,并且字符串没有诸如nameattacks属性。

The function reads a line from input, converts it to a string (stripping a trailing newline), and returns that. 该函数从输入中读取一行, 将其转换为字符串 (带末尾的换行符),然后将其返回。 When EOF is read, EOFError is raised. 读取EOF时,将引发EOFError。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 'str' object 在使用 dataframe 字符串名称时没有属性 'loc' - 'str' object has no attribute 'loc' when using dataframe string name 类实例没有用于在class-python外传递对象的属性&#39;function_name&#39; - Class instance has no attribute 'function_name' for passing object outside class- python AttributeError: 'str' object 没有属性 'str' - 调用没有“”的变量 - AttributeError: 'str' object has no attribute 'str' - call the variable without "" 在类的 str() 函数中使用实例名称 - Using instance name in str() function of a class Python AttributeError:“str”对象没有属性“_sa_instance_state” - Python AttributeError: 'str' object has no attribute '_sa_instance_state' 在python中,如果实例数据属性与类数据属性具有相同的名称,那么我们可以为这样的对象访问两者 - In python if a instance data attribute has the same name as the class data attribute, then can we access both for such an object 应用 function 'str' object 没有属性 'str' - Apply function 'str' object has no attribute 'str' 预处理类错误,“AttributeError:‘function’对象没有属性‘str’” - preprocessing class error, "AttributeError: 'function' object has no attribute 'str'" 是否可以使用具有有效属性名称的变量来调用类属性? - Is it possible to call a class attribute by using a variable which has a valid attribute name? AttributeError: 'str' object 没有属性 'contains' 使用 Lambda 将 function 应用于 df 列时 - AttributeError: 'str' object has no attribute 'contains' when applying a function to a df column using Lambda
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM