Reputation: 2424
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
Upvotes: 6
Views: 13608
Reputation: 69735
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
Upvotes: 0
Reputation: 78546
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?
Upvotes: 9
Reputation: 48067
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
Upvotes: 5