使用导入随机,使用随机选择抛出属性

2024-10-01 11:29:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

更新:原来我在逻辑.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公司名称:

^{pr2}$

在数据结构.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]

Tags: pyimportselfrightgetreturnvalueline
1条回答
网友
1楼 · 发布于 2024-10-01 11:29:55

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

这可能是一个问题的原因。在

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

相关问题 更多 >