日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python在开头声明全局变量_全局变量声明Python

發布時間:2025/3/21 python 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python在开头声明全局变量_全局变量声明Python 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

我有下面的代碼片段,可以創建一個筆記并添加到筆記本中.

我的問題與全局變量last_id更相關.當我將它聲明為類變量時,即在Class Note中,我得到以下錯誤但是當我在類外聲明時,我的代碼工作正常.

以下是我的澄清:

>為什么不接受類變量.

>當我在函數中將其聲明為全局變量時,為什么需要定義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")

總結

以上是生活随笔為你收集整理的python在开头声明全局变量_全局变量声明Python的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。