已检查以下主题以代替我在下面的问题。
请耐心等待,因为我是 Python 的绝对初学者。我刚刚开始处理课程,我认为一个简单的家庭财务模拟器对我来说是一个很好的起点。下面是我的代码:
class Family(object):
def __init__(self,name,role,pay,allowance):
self.name = name
self.role = role
self.pay = pay
self.allowance = allowance
def describe(self):
print self.name + " is the " + self.role + " of the family. He brings home " + str(self.pay) + " in wages and has a personal allowance of " + str(self.allowance) + "."
class Parent(Family):
def gotRaise(self,percent):
self.pay = self.pay * int(1 + percent)
print self.name + " received a pay increase of " + str((100*percent)) + ("%. His new salary is ") + str(self.pay) + "."
def giveAllowance(self,val,target):
if hasattr(target, Family):
self.pay = self.pay - int(val)
target.pay = target.pay + int(val)
print self.name + " gave " + target.name + " an allowance of " + str(val) + "." + target.name + "'s new allowance is " + str(target.allowance) + "."
else: print ""
class Child(Family):
def stealAllowance(self,val,target):
self.allowance = self.allowance + int(val)
target.allowance = target.allowance - int(val)
def spendAllowance(self,val):
self.allowance = self.allowance - int(val)
monty = Parent("Monty","Dad",28000,2000)
monty.describe() # 'Monty is the Dad of the family. He brings home 28000 in wages and has a personal allowance of 2000.'
monty.giveAllowance(1000,jane) # Produces a "NameError: name 'jane' is not defined" error.
问题的关键是 giveAllowance() 函数。我一直在尝试找到一种方法来检查 Family 的目标实例是否存在,如果存在则返回值转移,如果不存在则返回普通字符串。但是,hasattr()、try - 除了 NameError、isinstance(),甚至 vars()[target] 都无法解决上面的 NameError。
我是否在这里遗漏了一些我应该在课程方面做的事情,即。检查另一个类中的实例时出现异常,语法错误等?如果可能的话,我想远离字典,除非它们是最后的手段,因为从上面的链接之一看来,这是唯一的方法。
谢谢!