Global variable declaration Python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I have the below piece of code that creates a note and adds to a notebook.

My question is more related to the global variable last_id. When I declare it as class variable i.e. inside Class Note, I get the following error but when I declare outside the class, my code works fine.

Here are my clarifications:

    • Why does not it accept the class variable.
    • Why do I need to defined last_id, when I declare it as a global variable inside my function?
  Error:   
C:Python27BasicsOOPformytesting>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")    

Answers

python is a bit more explicit about where attributes come from than other object oriented languages; you can have a class level counter, like so:

from itertools import count

class Foo(object):
    last_id = count()

    def __init__(self):
        self.id = self.last_id.next()

you must refer to last_id as self.last_id, so that python knows to look on the instance (and since it s not already there, the class).

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/11872808/global-variable-declaration-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils