6

I have a simple class, and every time I create an instance of that class, I want the class variable to increment how is should i do that with this code:

class Person:

    person_count = 0

    def __init__(self, username):
        self.username = username

ashley = Person("Ash")
daphne = Person("Daph")

Person.person_count #I want this to be 2
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
teddybear123
  • 2,314
  • 6
  • 24
  • 38

3 Answers3

9

Simply increment the class variable in __init__:

class Person(object):

    person_count = 0

    def __init__(self, username):
        self.username = username
        Person.person_count += 1  # here

ashley = Person("Ash")
daphne = Person("Daph")

print(Person.person_count)
# 2

And don't forget to subclass from object if you're on Python 2.

See What is the purpose of subclassing the class "object" in Python?

Community
  • 1
  • 1
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
5

You will have to increment the class's variable within the __init__ as:

class Person:
    person_count = 0
    def __init__(self, username):
        self.username = username
        self.__class__.person_count += 1
        # OR, 
        # Person.person_count += 1

Example:

>>> ashley = Person("Ash")
>>> ashley.person_count
1
>>> daphne = Person("Daph")
>>> daphne.person_count
2

You may also extract the count directly using class as:

>>> Person.person_count
2
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

Use the __init__ method in order to increase your class variable:

class Person:
    person_count = 0
    def __init__(self, username):
        self.username = username
        Person.person_count += 1

A class variable can be access using the name of the class, so in this case Person. Keep in mind that you can also access this class variable from the instance, so:

>>> p1 = Person('person1')
>>> Person.person_count
1
>> p1.person_count
1
>> p2 = Person('person2')
>>> Person.person_count
2
>> p1.person_count
2
>> p2.person_count
2
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228