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
If you are familiar with other programming languages, such as C++ or Javascript, you may find yourself looking for an increment operator. This operator typically is written as a++ , where the value of a is increased by 1. In Python, however, this operator doesn't exist.
There are two ways to use the increment operator; prefix and postfix increment. The prefix increment looks like ++variablename; while the postfix increment looks like variablename++; . Both of these operations add one to the value in the variable. The difference between the two is the order of how it works.
Also python does come up with ++/-- operator.
Example 01: In the code area, write out the below python code to increment 1 in an integer type variable. We have added the python support in our spyder page first. You can see we have defined an integer x having a value of 0. After that, we have incremented this variable x with 1 using the “+=” operator within.
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With