鱼C论坛

 找回密码
 立即注册
查看: 4963|回复: 9

[已解决]AttributeError: module 'random' has no attribute 'randint'

[复制链接]
发表于 2023-10-1 11:50:50 | 显示全部楼层
在Python中,使用random库的randint函数来生成随机整数。根据你提供的错误信息,可能会发生这个错误的原因是程序引入了名为“random.py”的文件,该文件的名称与Python核心库的模块名称相同,导致系统找不到正确的模块。

为解决这个问题,可以将程序文件的名称更改为与模块名称不同的名称,并确保在引用random模块时使用正确的语法。下面提供一些修改建议:

1. 将程序文件名更改为“example.py”或其他与“random”模块名称不同的名称。
2. 移除导入中的别名。
3. 在调用randint()函数时,使用random.randint()的形式表示调用正确的模块。

以下是修改后的代码示例:
  1. import random
  2. class Fish:
  3.     def __init__(self):
  4.         self.x = random.randint(0, 10)
  5.         self.y = random.randint(0, 10)
  6.     def move(self):
  7.         self.x -= 1
  8.         print("我的位置是", self.x, self.y)
  9. class Goldfish(Fish):
  10.     pass
  11. class Carp(Fish):
  12.     pass
  13. class Salmon(Fish):
  14.     pass
  15. class Shark(Fish):
  16.     def __init__(self):
  17.         self.hungry = True
  18.     def eat(self):
  19.         if self.hungry:
  20.             print("吃货的梦想就是天天有得吃^_^")
  21.             self.hungry = False
  22.         else:
  23.             print("太撑了,吃不下了!")
  24. fish = Fish()
  25. fish.move()
  26. goldfish = Goldfish()
  27. goldfish.move()
  28. shark = Shark()
  29. shark.eat()
  30. shark.eat()
  31. # 创建10条鱼
  32. fishes = []
  33. for i in range(10):
  34.     if random.randint(0, 1) == 0:
  35.         fishes.append(Carp())
  36.     else:
  37.         fishes.append(Salmon())
  38. for fish in fishes:
  39.     fish.move()
复制代码

希望这能帮助你解决问题。

球一个最佳答案谢谢啦!这对我非常重要!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-9-27 02:36

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表