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)
在执行此代码时,出现错误,因为“ NameError:未定义名称'self'” 我不明白为什么我会收到这个错误,因为“ self”被用作类的“ self reference”,而我已经做到了。
这段代码只是一个简单的问题,我在研究类和方法时必须解决。
答案 0 :(得分:2)
self
应该是使用self
(例如self.balance
)的类中任何方法的第一个参数,因此您的withdraw
和deposit
方法是缺少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!!"
请注意,您在self.deposit()
语句中缺少该金额。 self
方法中的self.balance
中还缺少deposit
。
答案 1 :(得分:0)
deposit和withdraw是成员函数。因此,成员函数的第一个参数应为self。 然后,存款函数在函数定义中不需要参数。这是更正的代码。如果为错误发布堆栈跟踪信息,也将很有帮助。这将有助于快速解决此问题。
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!!"
帐户_1 =帐户(“ sammy”,500) 打印(帐户_1) 帐户_1。所有者 帐户_1。余额 Account_1.deposit() 帐户_1。提款(650) Account_1.withdraw(300)