python在开头声明全局变量_全局变量声明Python
我有下面的代碼片段,可以創(chuàng)建一個筆記并添加到筆記本中.
我的問題與全局變量last_id更相關(guān).當(dāng)我將它聲明為類變量時,即在Class Note中,我得到以下錯誤但是當(dāng)我在類外聲明時,我的代碼工作正常.
以下是我的澄清:
>為什么不接受類變量.
>當(dāng)我在函數(shù)中將其聲明為全局變量時,為什么需要定義last_id?
錯誤:
C:\Python27\Basics\OOP\formytesting>python notebook.py
Traceback (most recent call last):
File "notebook.py", line 38, in
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")
總結(jié)
以上是生活随笔為你收集整理的python在开头声明全局变量_全局变量声明Python的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php 打印mysql错误日志_PHP
- 下一篇: mysql 1084_[LeetCode