我一直在获取这个错误,我完全不知道为什么,我有3个文件相互导入信息,但是这个主文件只从monster_01.py及其player.py获取信息。
TypeError: player_attack() missing 1 required positional argument: 'self'--主要代码--
'''Player class
Fall 2014
@author Myles Taft (mbt6)
'''
import random
import monster_01
class Player():
def __init__(self, strength = 0, player_hp = 0):
self.strength = 1
self.player_hp = 100
print(self.strength, self.player_hp)
def battle():
def player_attack(self):
print('success')
while self.enemy_hp > 0:
monster_01()
self.dice1 = random.randint(1,6)
self.dice2 = random.randint(1,6)
self.dice_sum = dice1 + dice2
self.attack = dice1 + dice2
self.decide_roll = input('Type "roll" to roll the dice:')
self.roll = print('First die:' + dice1, 'Second die:' + dice2, 'Sum of dice:' + dice_sum)
if self.roll == 2 or 4 or 6 :
print('Hit!')
self.enemy_hp == strength
print(enemy_hp)
elif self.roll == 1 or 3 or 5:
print('Miss!')
def player_block(self):
self.dice1 = random.randint(1,6)
self.dice2 = random.randint(1,6)
self.decide_roll = input('Type "roll" to roll the dice:')
self.roll = print('First die:' + dice1, 'Second die:' + dice2, 'Sum of dice:' + dice_sum)
if self.roll == 2 or 4:
print('Blocked!')
self.player_hp -= int((enemy_strength)/2)
if self.roll == 1 or 3:
self.player_hp -= int(enemy_strength)
def choice(self):
get_player_attack(get_player_attack)
self.player_choice = input('Do you attack or block?') #self.player_hp, self.strength)
if self.player_choice == 'attack':
self.player_attack()
elif self.player_choice == 'block':
self.player_block()
def get_player_attack(self):
player_attack()
choice(choice)
Player.battle()我已经在这个代码上和下了上百次,任何帮助都将不胜感激。
发布于 2014-11-12 01:25:42
问题在于您的get_player_attack方法:
def get_player_attack(self):
player_attack()它调用player_attack,就好像它是一个独立的函数,而不是另一个方法。但是player_attack是类Player的一种方法,因此只能在Player实例上调用。
这个函数应该被调用如下:
self.player_attack()还有,像这样的东西:
if self.roll == 2 or 4 or 6 :只是一个等待发生的问题。它应写成:
if self.roll in (2, 4, 6):否则,if-语句的条件将解释为:
if (self.roll == 2) or (4) or (6):它将始终评估为True。有关更多信息,请参阅How do I test one variable against multiple values?
最后,您不应该将所有的方法都放在另一个名为battle的函数中。我不知道您在这里试图做什么,但是方法定义应该就在类头下面:
class MyClass: # Class header
def method1(self): # Definition of the first method
...
def method2(self): # Definition of the next method
...
...我真的认为阅读一些关于Python类和OOP的教程会更好。以下是一些让你开始学习的方法:
发布于 2014-11-12 01:33:42
现在还不清楚你想在战斗中做什么。您还没有定义self参数,但也没有使用@static来指示您希望它是一个静态函数。您已经在can中定义了player_attack,所以它不能是一个实例方法。语法不正确。
如果您的意思是add ()是一个实例方法,那么添加一个self参数并提供一个方法主体或pass,然后使player_attack去缩进。
https://stackoverflow.com/questions/26877665
复制相似问题