Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing class variables dynamically in Python

Tags:

python

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
like image 672
teddybear123 Avatar asked Feb 12 '17 20:02

teddybear123


People also ask

Can you use ++ to increment in Python?

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.

How do you increment a class variable?

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.

Is there a ++ operator in Python?

Also python does come up with ++/-- operator.

How do you increment a variable value in Python?

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.


2 Answers

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?

like image 82
Moses Koledoye Avatar answered Sep 25 '22 13:09

Moses Koledoye


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
like image 35
Moinuddin Quadri Avatar answered Sep 24 '22 13:09

Moinuddin Quadri