use*_*619 7 python global-variables
我有下面的代码片段,可以创建一个笔记并添加到笔记本中.
我的问题与全局变量有关last_id.当我将它声明为类变量时,即在Class Note中,我得到以下错误但是当我在类外声明时,我的代码工作正常.
以下是我的澄清:
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
Run Code Online (Sandbox Code Playgroud)
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")
Run Code Online (Sandbox Code Playgroud)
Gor*_*ley 10
当你写作
global last_id
Run Code Online (Sandbox Code Playgroud)
在函数内部,您不会创建新的全局变量.你正在做的是"不是创建一个新的局部变量并将其与名称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
Run Code Online (Sandbox Code Playgroud)
python比其他面向对象的语言更明确地指出属性的来源; 你可以有一个班级计数器,如下:
from itertools import count
class Foo(object):
last_id = count()
def __init__(self):
self.id = self.last_id.next()
Run Code Online (Sandbox Code Playgroud)
你必须引用last_idas self.last_id,以便python知道查看实例(因为它不在那里,类).
| 归档时间: |
|
| 查看次数: |
50568 次 |
| 最近记录: |