Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local Variable referenced before assignment inside of a class

Here's the situation

class Person(object):
    NumRid = 1
    def __init__(self, name, rid = NumRid):
        self.name = name
        self.rid = rid
        NumRid += 1

class Investor(Person):
    pass

then I enter the interactive python session, and type in from file import * and then Investor('Bob') and it tells me that local variable NumRid is referenced before assignment, at NumRid += 1.

as far as I can tell from googling, NumRid should be in the local namespace of the class and accessible from the class function.... so what's up with this? do I need to declare both to be global; or is there a magic word I can type to make it look up NumRid in the class namespace if there is one?

like image 908
Zach Avatar asked Oct 12 '13 20:10

Zach


1 Answers

Inside the __init__ function, there is no NumRid, and yet you are trying to increment it.

It should be either self.NumRid += 1 if it is an instance variable, or Person.NumRid += 1 if it is a class variable (or, to future-proof against renaming the class: self.__class__.NumRid += 1).

like image 126
Ethan Furman Avatar answered Oct 24 '22 01:10

Ethan Furman