I would like to know how to increase/increment an attribute of a class.
I have a class called Account which has an attribute: self.code which is initialized at 0 and I want each time that an object is created the attribute increases.
so, for example:
account1=Account()
account2=Account()
account3=Account()
if I do account3.code I want to have 3 as a result.
Is there a possible way to do so? thank you in advance.
CodePudding user response:
you can do it like this:
class Example:
code = 0
def __new__(cls, *args, **kwargs):
cls.code = 1
return super().__new__(Example, *args, **kwargs)
def __del__(self):
cls.code -= 1
ex1 = Example()
print(ex1.code) # 1
ex2 = Example()
print(ex2.code) # 2
ex3 = Example()
print(ex3.code) # 3
CodePudding user response:
If you also want each Account instance to store the code at which it was created you can use it like this
class Account:
last_code = 0
def __init__(self) -> None:
self.code = Account.last_code 1
Account.last_code = self.code
a = Account()
b = Account()
c = Account()
print(a.code) # 1
print(b.code) # 2
print(c.code) # 3
CodePudding user response:
You can define a static variable for the Account object and increment it everytime you create a new object like this:
class Account:
code = 0
self.id = 0
def __init__(self):
self.id = Account.code
Account.code = 1
def __del__(self):
Account.code -= 1
The code variable defines how many instances were created. Every account has an id
