python - 有没有办法修复由于范围而导致的名称错误?

标签 python

我有一个创建玩家对象的函数,但是在引用该对象时,我收到一个 NameError。我认为这是由于本地范围而发生的,但全局应该修复它......

我刚刚开始使用 OOP,这段代码可以在 python shell 中运行,但不能在脚本模式下运行。

endl = lambda a: print("\n"*a)

class Score:
    _tie = 0
    def __init__(self):
        self._name = ""
        self._wins = 0
        self._loses = 0

    def get_name(self):
        print
        self._name = input().upper()

    def inc_score(self, wlt):
        if wlt=="w": self._wins += 1
        elif wlt=="l": self._loses += 1
        elif wlt=="t": _tie += 1
        else: raise ValueError("Bad Input")

def player_num(): #Gets number of players
    while True:
        clear()
        endl(10)
        print("1 player or 2 players?")
        endl(5)
        pnum = input('Enter 1 or 2: '.rjust(55))
        try:
            assert int(pnum) == 1 or int(pnum) == 2
            clear()
            return int(pnum)
        except:
            print("\n\nPlease enter 1 or 2.")

def create_player():  #Creates players
    global p1
    p1 = Score()
    yield 0          #stops here if there is only 1 player
    global p2
    p2 = Score()

def pr_():          #testing object
    input(p1._wins)
    input(p2._wins)


for i in range(player_num()):
    create_player()
    input(p1)
input(p1._wins())
pr_()

无论我在哪里引用 p1,我都应该获得所需的对象属性,但我收到此错误

Traceback (most recent call last):
  File "G:/Python/TicTacTwo.py", line 83, in <module>
    input(p1)
NameError: name 'p1' is not defined

最佳答案

您的问题不在于global,而是在于create_player()中的yield,它将函数变成生成器.

可以做什么:

实际上通过执行list(create_player())来运行生成器(不太好,但有效)。

但我建议你重新设计你的代码,例如通过调用具有玩家数量的方法:

def create_player(num):  #Creates players
    if num >= 1:
        global p1
        p1 = Score()
    if num >= 2:
        global p2
        p2 = Score()

如果解决了这个问题,接下来的问题将会是

1) input(p1) 将打印 p1 的字符串表示形式,并且输入将丢失,您可能需要 p1.get_name() 改为。

2) input(p1._wins()) 将引发 TypeError: 'int' 对象不可调用

关于python - 有没有办法修复由于范围而导致的名称错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57249953/

相关文章:

python - 简洁灵活的结构体定义

python - 查找 1 到 ~2^128 之间的素数

python - 如何从使用python从openCV获得的颜色检测结果区域获取屏幕坐标?

python - 如何使用 SQLAlchemy 测试无效记录插入?

python - 如何正确舍入半 float ?

python - 运行包含超过一百万个测试用例的测试套件

python - 为什么这个来自 Google Secret Manager API 的 gRPC 调用在 Apache 运行时挂起?

python - 使用 pandas 基于过滤和用户输入添加三列

python - 写从 0 到 1000000000 的数字

python - 全屏 Firefox Python Selenium