如何解决继续从类变量获取NameError吗?
所以我试图通过创建一个类来完全理解Python OOP,但是我对自己不断收到的错误感到困惑。仍在学习,所以请尝试在这里了解我的初学者情况。
class Investor:
def __init__(self,name,principle,returns):
self.name = name
self.principle = principle
self.returns = returns
def info(self):
return '{} {}'.format(self.name,self.principle)
def deposit(self):
global deposit_amount
deposit_amount = float(input('Amount: '))
return deposit_amount + self.principle + self.returns
def withdraw(self):
global withdraw_amount
withdraw_amount = float(input('Withdraw amount: '))
return self.principle + self.returns + deposit_amount - withdraw_amount
def balance(self):
if deposit_amount > 0 or withdraw_amount > 0:
return self.principle + self.returns + deposit_amount - withdraw_amount
else:
return self.principle + self.returns
investor1 = Investor('John',5000,0)
while True:
prompt = input('What would you like to do?\n')
if prompt == 'Balance':
try:
print(investor1.balance())
except ValueError:
print(investor1.info())
elif prompt == 'Deposit':
print(investor1.deposit())
elif prompt == 'Withdraw':
print(investor1.withdraw())
输出:
What would you like to do?
当我第一次输入Deposit
,然后依次输入Withdraw
和 然后 Balance
时,代码运行正常。
但是,当我首先输入Balance
时,出现以下错误:
return self.principle + self.returns + deposit_amount - withdraw_amount
NameError: name 'deposit_amount' is not defined
有人帮忙吗?
解决方法
您在调用global deposit_amount
方法时首先声明deposit(self)
。
该语句将变量置于全局范围内。在调用deposit(self)
之前,永远不会在balance(self)
的局部函数作用域或全局作用域中都没有定义变量。因此,您会收到此错误。
首先,这与OOP python没有关系,但这只是范围的问题。
为此,我建议您将变量作为类实例成员:
def __init__(self,name,principle,returns):
self.name = name
self.principle = principle
self.returns = returns
self.deposit_amount = 0
self.withdraw_amount = 0
,
首先输入return highest_county,highest_turnout
时,既没有定义Balance
也没有deposit_amount
,withdraw_amount
定义中的if
语句都需要
“ deposit_amount”是函数deposit的局部变量。因此,除非您运行存款fn。首先,就系统而言不存在。因此请尝试全局初始化。 如果您想阅读局部变量和全局变量,请参考: https://www.tutorialspoint.com/global-and-local-variables-in-python#:~:text=There%20are%20two%20types%20of,function%20where%20it%20is%20defined。
,如果您尝试在存款前退出,deposit_amount
变量在函数withdraw
中是未知的。您必须添加global deposit_amount
并在某个位置声明此变量,但它不是OOP样式。最好的办法是将此变量作为__init__
添加到您的self.deposit_amount = 0
中。然后由self
在类Investor
中定义的所有函数中引用它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。