Roshan
Roshan

Reputation: 724

UnboundLocalError : Getting exception in a class attribute declaration

class Human:
    population = 0
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender
        population += 1

human = Human("Name", 12, "M")
print(Human.population)

The above code throws UnboundLocalError Exception. Full statement : UnboundLocalError: local variable 'population' referenced before assignment

How can I fix this issue?

Upvotes: 1

Views: 94

Answers (1)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20500

Human is a class attribute accessible via Human.population inside the class

It is accessible outside class via human.population or Human.population

class Human:
    population = 0
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender
        #Access class attribute via ClassName inside class definition
        Human.population += 1

human = Human("Name", 12, "M")
#Access class attribute via ClassName outside class definition
print(Human.population)
#Access class attribute via Class instance outside class definition
print(human.population)

The output will be

1
1

Upvotes: 3

Related Questions