gpt4 book ai didi

python - 使用 import random,使用 random.choice 抛出 AttributeError

转载 作者:行者123 更新时间:2023-12-04 18:08:49 26 4
gpt4 key购买 nike

所以,我遇到了一个非常奇怪的错误。出于某种原因,python 没有将 random 作为模块导入,在我看来,它是作为函数( as seen here )导入的。为什么要这样做?使用 import randomrandom.choice() 在其他模块中工作正常。为什么不在这里?

更新:原来我在 logic.py 中再次定义了随机数。我忘了我这样做了,因为我不再使用它了。将其注释掉,它工作正常。

回溯:

Traceback (most recent call last):
File "H:\workspace37\RockPaperScissors\irps\driver.py", line 20, in <module>
print "%r" % dtree.root.get_value(history)
File "H:\workspace37\RockPaperScissors\irps\datastructures.py", line 69, in get_value
return self.operation(self.left.get_value(history), self.right.get_value(history))
File "H:\workspace37\RockPaperScissors\irps\datastructures.py", line 69, in get_value
return self.operation(self.left.get_value(history), self.right.get_value(history))
File "H:\workspace37\RockPaperScissors\irps\logic.py", line 53, in either
return random.choice((a, b))
AttributeError: 'function' object has no attribute 'choice'

我试图包含相关的代码。

逻辑.py:

import random 
#from random import choice # works if I change random.choice(...) to just choice(...)

ROCK = 'R'
PAPER = 'P'
SCISSORS = 'S'
RPS_TUPLE = (ROCK, PAPER, SCISSORS)
RPS_SET = set((ROCK, PAPER, SCISSORS))
PLAYER = 0
OPPONENT = 1
PLAYERS = (PLAYER, OPPONENT)

def assert_in_set(a, b):
assert a in RPS_SET
assert b in RPS_SET

def neither(a, b):
assert_in_set(a, b)
diff = RPS_SET.difference((a, b))
print "diff = ", diff
return random.choice(tuple(diff))

def either(a, b):
assert_in_set(a, b)
return random.choice((a, b)) #line 53

#EDITED TO INCLUDE THESE LINES FURTHER DOWN
def random(a, b):
return random.choice(RPS_TUPLE)

ALL_OPERATORS = (neither, either)

数据结构.py

from collections import deque
from logic import RPS_TUPLE, ALL_OPERATORS, PLAYERS
import random
import sys

class OperationNode(TreeNode):

def __init__(self, parent, left, right, operation):
super(OperationNode, self).__init__(parent, left, right)
self.operation = operation

def get_value(self, history):
return self.operation(self.left.get_value(history), self.right.get_value(history)) # line 69


class TerminalNode(TreeNode):

def __init__(self, parent, player, position):
super(TerminalNode, self).__init__(parent, None, None)
self.player = player
self.position = position

def get_value(self, history):
# history is a deque of tuples
return history[self.position][self.player]

最佳答案

你在logic.py中定义了随机函数吗?

这可能是问题的原因。

>>> def random():
... pass
...
>>> random.choice
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'choice'

关于python - 使用 import random,使用 random.choice 抛出 AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19674011/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com