gpt4 book ai didi

python - 全局变量声明Python

转载 作者:太空狗 更新时间:2023-10-29 21:16:10 26 4
gpt4 key购买 nike

我有下面一段代码可以创建一个笔记并添加到笔记本中。

我的问题更多地与全局变量 last_id 有关。当我将它声明为类变量时,即在 Class Note 中,我收到以下错误,但是当我在类外声明时,我的代码工作正常。

这里是我的澄清:

  1. 为什么它不接受类变量。
  2. 当我在函数中将其声明为全局变量时,为什么需要定义 last_id

错误:

C:\Python27\Basics\OOP\formytesting>python notebook.py
Traceback (most recent call last):
File "notebook.py", line 38, in <module>
firstnote = Note('This is my first memo','example')
File "notebook.py", line 10, in __init__
last_id += 1
NameError: global name 'last_id' is not defined

code.py

import datetime
last_id = 0
class Note:

def __init__(self, memo, tags):
self.memo = memo
self.tags = tags
self.creation_date = datetime.date.today()
global last_id
last_id += 1
self.id = last_id

#global last_id
#last_id += 1
#self.id = last_id

def __str__(self):
return 'Memo={0}, Tag={1}, id={2}'.format(self.memo, self.tags,self.id)


class NoteBook:
def __init__(self):
self.notes = []

def add_note(self,memo,tags):
self.notes.append(Note(memo,tags))

def __iter__(self):
for note in self.notes:
yield note



if __name__ == "__main__":
firstnote = Note('This is my first memo','example')
print(firstnote)
Notes = NoteBook()
print("Adding a new note object")
Notes.add_note('Added thru notes','example-1')
Notes.add_note('Added thru notes','example-2')
for note in Notes.notes:
print(note.memo,note.tags)

for note in Notes:
print(note)

print("Adding a new note object----End")

最佳答案

当你写作时

global last_id

在您的函数内部,您并未创建新的全局变量。您正在做的是说“不是创建一个新的局部变量并将其关联到名称 last_id,而是将该名称关联到封闭范围中名称为 的预先存在的变量last_id

如果还没有名为 last_id 的变量,则 global last_id 在您写入之前不会引用任何内容。但是,如果您写入它,它将在全局范围内创建。例如:

>>> def x():
... global X
... X = 1
...
>>> x()
# No error
>>> X
1 # X is now defined
>>> def y():
... global Y
... print Y
...
>>> y()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in y
NameError: global name 'Y' is not defined

关于python - 全局变量声明Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11872808/

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