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

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.