python声明一个全局变量_全局变量声明Python

下面的代码创建了一个便条并添加到笔记本中。

我的问题与全局变量last_id更相关。当我将其声明为类变量(即类内注释)时,会得到以下错误,但当我在类外声明时,我的代码可以正常工作。

以下是我的澄清:为什么它不接受类变量。

当我在函数中声明为全局变量时,为什么需要定义last_id?

Error: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.pyimport 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")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值