TypeError:Attack()缺少1个必需的位置参数:'self' [英] TypeError: attack() missing 1 required positional argument: 'self'
问题描述
我收到此错误
TypeError: attack() missing 1 required positional argument: 'self'
这是我的代码
class Enemmy :
life = 3
self = ""
def attack(self):
print ("ouch!!!!")
self.life -= 1
def checkLife(self):
if self.life <= 0 :
print ("dead")
else:
print (self.life)
enemy=Enemmy
enemy.attack()
我检查并查看了大多数地方,说我忘记了在def攻击
中的自我,或者我需要创建一个obj以便将类放入
中,我将python 3.4与py一起使用charm
i实际上是从教程中获得的代码,我不知道我的错误是什么
i checked and looked most places says i forgot the self in the def attack or that i need to make an obj to put the class in im useing python 3.4 with py charm i actually got this code from a tutorial and i dont know what is my mistake
推荐答案
您没有实例化您的 Enemy
类。您正在创建对类本身的新引用。然后,当您尝试调用方法时,您将在没有实例的情况下调用该方法,该实例应该被放入 attack()<的
self
参数中/ code>。
You're not instantiating your Enemy
class. You are creating a new reference to the class itself. Then when you try and call a method, you are calling it without an instance, which is supposed to go into the self
parameter of attack()
.
更改
enemy = Enemy
到
enemy = Enemy()
也(如Kevin在评论中指出的那样)您的 Enemy
类可能应该具有 init
方法来初始化其字段。例如
Also (as pointed out in by Kevin in the comments) your Enemy
class should probably have an init
method to initialise its fields. E.g.
class Enemy:
def __init__(self):
self.life = 3
...
这篇关于TypeError:Attack()缺少1个必需的位置参数:'self'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!