我有下面的一段代码,它创建一个笔记并添加到笔记本中。
我的问题与全局变量更相关last_id
。当我将它声明为类变量时,即在类注释中,我收到以下错误,但是当我在类之外声明时,我的代码工作正常。
以下是我的澄清:
- 为什么它不接受类变量。
last_id
当我在函数中将其声明为全局变量时,为什么需要定义?
Error:
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")