You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

导入自定义类后调用函数触发AttributeError:str对象无make_turn属性

问题:导入类运行自定义函数时出现AttributeError错误

尝试从另一个文件导入类和方法运行自定义函数,但无论修改前置文件,PyCharm始终返回相同错误。

代码片段

randomwalk.py

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

simulation.py

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' 对象没有属性 'make_turn'

进程已结束,退出代码 1

解决方法

  1. 错误根源
    Game类的__init__方法要求传入Player、Coin、Dice的实例对象,但你传入的是字符串'Alex'、'heads'和数字3,导致self.player被赋值为字符串,调用make_turn方法时自然会触发AttributeError——字符串没有这个方法。

  2. 修正步骤

    • 首先在simulation.py中导入所有需要的类:
      from randomwalk import Game, Player, Coin, Dice
      
    • 创建对应类的实例,再传入Game的构造函数:
      player = Player()
      coin = Coin()
      dice = Dice()
      game = Game(player, coin, dice)
      
    • 另外,Game类的play方法存在逻辑错误:for循环的第一次迭代就执行了return,导致只运行1次回合而非预期的20次,需要把return移到循环外面:
      def play(self):
          for i in range(20):
              self.player.make_turn(self.coin, self.dice)
          return self.player.position
      
  3. 修正后的完整代码

    修正后的simulation.py

    from randomwalk import Game, Player, Coin, Dice
    
    
    def startSimulation():
        num_games = 100
        total_position = 0
        for i in range(num_games):
            player = Player()
            coin = Coin()
            dice = Dice()
            game = Game(player, coin, dice)
            end_position = game.play()
            total_position += end_position
    
        average_position = total_position / num_games
        print(f'Average position after {num_games} games (20 moves per game) is {average_position}')
    
    startSimulation()
    

    修正后的randomwalk.py中Game类的play方法

    class Game:
        def __init__(self, player, coin, dice):
            self.player = player
            self.coin = coin
            self.dice = dice
    
        def play(self):
            for i in range(20):
                self.player.make_turn(self.coin, self.dice)
            return self.player.position
    

内容的提问来源于stack exchange,提问作者Arbab Qaisar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 13:25:11