【发布时间】:2020-08-27 06:23:55
【问题描述】:
所以我试图通过创建一个类来完全理解 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 和 then Balance 代码工作得很好。
但是,当我首先输入Balance 时,出现以下错误:
return self.principle + self.returns + deposit_amount - withdraw_amount
NameError: name 'deposit_amount' is not defined
有什么帮助吗,伙计们?
【问题讨论】:
-
在你的方法中创建全局变量完全忽略了使用类的意义。重点是封装状态,而不是使用全局状态。
标签: python function class methods