class BankAccount:
no_of_accounts = 0
def __init__(self, name, balance = 0):
self.name = name
if balance >= 0:
self.balance = balance
else:
self.balance = 0
def show_name(self):
if self.name:
print(self.name)
def show_balance(self):
if self.balance:
print(self.balance)
def deposit(self,amount):
if amount >= 0:
if isinstance(amount,int) == True:
self.balance += amount
def withdraw(self,amount):
if amount >= 0 and self.balance >= amount:
self.balance -= amount
In this code, I want to add 1 to no_of_accounts each time an object is created in a class, what should I do? Every time an object is created, the init method is used, so if you add no_of_accounts += 1 inside the init method, no_of_accounts are class variables, so an error appears.
python
Class variable is class name.Accesses by variable name.
class BankAccount:
no_of_accounts = 0
def __init__(self, name, balance = 0):
BankAccount.no_of_accounts += 1
self.name = name
if balance >= 0:
self.balance = balance
else:
self.balance = 0
You can do it with.
© 2024 OneMinuteCode. All rights reserved.