未定义Python变量名

2024-05-29 09:55:25 发布

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

这是我的(简称)代码。在

race1names = ["Jeff", "Paul", "Mark"]
race1odds = [5, 6, 7]

class Horse:
    def __init__(self, name, odds, age, weight):
        self.name = name
        self.odds = odds
        self.age = age
        self.weight = weight

def Horsecreate():
    hcount = 0
    horse = {}
    while hcount < 3:
        cname = race1names[hcount]
        codds = race1odds[hcount]
        cage = 3
        cweight = 3

        for i in range(0, 3):
            horse[i] = Horse(cname, codds, cage, cweight)

        hcount +=1

Horsecreate()

print(horse0.name)
print(horse1.name)

我的错误是:

^{pr2}$

我试了几件事,但没用。据我所知这应该行得通吗?在

更新

在看过你们的答案后,我用代码改变了一些东西。新错误。在

而且,我也没有澄清我的意图。我基本上想运行这个函数,它将递归地拉取各种变量,将它们作为一个新的“horseactor”一起添加到一个新的类实例中(我对编码还比较陌生)。在

在本例中,我希望它创建horse[0],它将是“Jeff”,赔率为5。在

马[1]谁的几率是6

还有,马[2],谁的几率是7

(来自两个简单的测试列表“race1names”和“race1odds”)

最终我想要多匹马,都有自己独立的价值观。这只是一个测试脚本,但是以后会增加更多的复杂性。在

更新后的代码是:

race1names = ["Jeff", "Paul", "Mark"]
race1odds = [5, 6, 7]

horse = {}

class Horse:
    def __init__(self, name, odds, age, weight):
        self.name = name
        self.odds = odds
        self.age = age
        self.weight = weight

def Horsecreate():
    for i in range(0, 2):
        cname = race1names[i]
        codds = race1odds[i]
        cage = 3
        cweight = 3
        horse[i] = Horse(cname, codds, cage, cweight)

        return horse


horse = Horsecreate()

print(horse[0].name)
print(horse[1].name)
print(horse[2].name)

出现错误时:

Jeff
Traceback (most recent call last):
  File "file", line 27, in <module>
    print(horse[1].name)
KeyError: 1

这看起来很简单,但还是尝试了一些事情,但都没有成功。在

显然,“杰夫”是印刷出来的,显示出某种作品。在


删除退货后,它现在给我:

Traceback (most recent call last):
  File "file", line 26, in <module>
    print(horse[0].name)
TypeError: 'NoneType' object is not subscriptable

谢谢,非常感谢您的快速帮助


作为对@gilch的回应,我取消了重新分配并返回。现在它给了我一个错误:

print(horse[0].name)
KeyError: 0

好像它没有被分配。 以下是当前代码:

race1names = ["Jeff", "Paul", "Mark"]
race1odds = [5, 6, 7]
global horse
horse = {}

class Horse:
    def __init__(self, name, odds, age, weight):
        self.name = name
        self.odds = odds
        self.age = age
        self.weight = weight

def Horsecreate():
    for i in range(0, 2):
        cname = race1names[i]
        codds = race1odds[i]
        cage = 3
        cweight = 3
        horse[i] = Horse(cname, codds, cage, cweight)


print(horse[0].name)
print(horse[1].name)
print(horse[2].name)

Tags: nameselfagedefcnameprintweightcage
1条回答
网友
1楼 · 发布于 2024-05-29 09:55:25

Horsecreate中添加global horse,并将打印改为print(horse[0].name)

horse变量是Horsecreate函数的局部变量。函数在Python中创建局部作用域。在函数内部创建的赋值在函数外部不可见。global关键字使其在函数外部可见,而不是在本地。您也可以在函数外部声明horse = {}。在

当您说horse0时,Python如何知道0不仅仅是新变量名的一部分?您必须包含[]订阅运算符,与分配时相同。在


你的嵌套循环也没有意义。你会扔掉所有在最后一个while循环之前制造的马。在


更新后的版本在for循环中有一个返回。这将立即结束循环,因此您只得到一个循环,而不是您想要的三个。如果是全局的,则根本不需要返回并重新分配horse。但是如果在循环之后返回它,它不需要是全局的。做一个或另一个。在

相关问题 更多 >

    热门问题