问题描述
我收到这个错误
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()
我检查并查看了大多数地方说我在防御攻击中忘记了自我或者我需要制作一个 obj 来放置课程我使用带有 py 魅力的 python 3.4我实际上从教程中得到了这段代码,但我不知道我的错误是什么
i checked and looked most places says i forgot the self in the def attackor that i need to make an obj to put the class inim useing python 3.4 with py charmi actually got this code from a tutorial and i dont know what is my mistake
推荐答案
你没有实例化你的 Enemy
类.您正在创建对类本身的新引用.然后当你尝试调用一个方法时,你是在没有实例的情况下调用它,它应该进入 attack()
的 self
参数.
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
...
这篇关于类型错误:attack() 缺少 1 个必需的位置参数:'self'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!