我试图通过从另一个文件导入类和方法来运行自定义函数。无论我在前一个文件中进行什么更改,我都会继续从 pycharm 收到相同的错误消息。有人可以帮我吗? 第一个文件中的代码片段:
import random
class Coin:
def __init__(self):
pass
def flip(self):
return random.choice(['heads', 'tails'])
class Dice:
def __init__(self):
pass
def roll(self):
return random.randint(1, 6)
class Player:
def __init__(self):
self.position = 0
def update_position(self, delta):
self.position += delta
def make_turn(self, coin, dice):
coin_toss = coin.flip()
dice_roll = dice.roll()
if coin_toss == 'heads':
movement = 1
else:
movement = -1
self.update_position(movement * dice_roll)
class Game:
def __init__(self, player, coin, dice):
self.player = player
self.coin = coin
self.dice = dice
pass
def play(self):
for i in range(20):
self.player.make_turn(self.coin, self.dice)
return self.player.position
第二个文件的片段:
from randomwalk import Game
def startSimulation():
num_games = 100
position = 0
for i in range(num_games):
games = Game('Alex', 'heads', 3)
end_position = games.play()
position += end_position
average_position = position/num_games
print('Average position after'+ str(num_games)+ 'games(20 moves per game) is' + str(average_position))
startSimulation()
错误信息:
D:\Python\pythonProject\venv\Scripts\python.exe D:\Python\pythonProject\simulation.py
Traceback (most recent call last):
File "D:\Python\pythonProject\simulation.py", line 15, in <module>
startSimulation()
File "D:\Python\pythonProject\simulation.py", line 9, in startSimulation
end_position = games.play()
^^^^^^^^^^^^
File "D:\Python\pythonProject\randomwalk.py", line 36, in play
self.player.make_turn(self.coin, self.dice)
^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'make_turn'
Process finished with exit code 1
使用
Game
创建 games = Game('Alex', 'heads', 3)
对象时,参数应该是 Player, Coin, and Dice
的实例,而不是字符串。
此外,
play
类中的Game
方法运行20圈循环,但return语句在第一圈后立即退出。返回应移至循环外,以在 20 圈后返回最终位置。