Reputation: 1
class Account():
def __init__(self,owner,balance):
self.owner = owner
self.balance = balance
def __str__(self):
return "Account owner : {}\nAccount balance: {}".format(self.owner,self.balance)
def deposit(amount):
print ("How much you want to deposit")
amount = int(input())
self.balance = (balance) + (amount)
return "Deposit Accepted\nThe new balance is {}".format(self.balance)
def withdraw(amount):
if (self.balance >= amount):
self.balance = self.balance - amount
return "Withdrawal Accepted\nThe new balance is {}".format(self.balance)
else:
return "Insufficient funds!!"
Account_1 = Account("sammy",500)
print(Account_1)
Account_1.owner
Account_1.balance
Account_1.deposit()
Account_1.withdraw(650)
Account_1.withdraw(300)
while executing this code i am getting error as "NameError: name 'self' is not defined" i dont understand why i a getting this error since 'self' is used as 'self reference'for a class and i've done it already.
this code is just a simple problem which i got to solve while studying classes and methods.
Upvotes: 0
Views: 327
Reputation: 71
deposit and withdraw are member functions. So member functions should have first argument as self. Then deposit function do not need an argument in the function definition. Here is the corrected code. Also it would be helpful if you post the stack trace for the error. That would help to zero in on the issue fast.
class Account():
def __init__(self,owner,balance):
self.owner = owner
self.balance = balance
def __str__(self):
return "Account owner : {}\nAccount balance: {}".format(self.owner,self.balance)
def deposit(self):
print ("How much you want to deposit")
amount = int(input())
self.balance = self.balance + amount
return "Deposit Accepted\nThe new balance is {}".format(self.balance)
def withdraw(self, amount):
if (self.balance >= amount):
self.balance = self.balance - amount
return "Withdrawal Accepted\nThe new balance is {}".format(self.balance)
else:
return "Insufficient funds!!"
Account_1 = Account("sammy",500) print(Account_1) Account_1.owner Account_1.balance Account_1.deposit() Account_1.withdraw(650) Account_1.withdraw(300)
Upvotes: 0
Reputation: 9520
self
should be the first argument to any method in a class that uses self
(e.g. self.balance
), so your withdraw
and deposit
methods are missing a self
:
def deposit(self,amount):
print ("How much you want to deposit")
amount = int(input())
self.balance += amount
return "Deposit Accepted\nThe new balance is {}".format(self.balance)
def withdraw(self,amount):
if (self.balance >= amount):
self.balance = self.balance - amount
return "Withdrawal Accepted\nThe new balance is {}".format(self.balance)
else:
return "Insufficient funds!!"
Note that you're missing the amount in your self.deposit()
statement. There's also a missing self
in self.balance
in your deposit
method.
Upvotes: 2