下面的主题已被检查代替我的问题。使用普通测试来检查实例是否存在
In Python, how do I check if an instance of my class exists?
我Python check instances of classes
熊,因为我在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(),除了NameError,isinstance(),甚至vars()[target]都不能解决上面的NameError问题。
我在这里错过了什么,我应该做的就类,即。从另一个类中检查实例时出现异常,语法错误等?如果可能的话,我想远离字典,除非它们是最后的手段,因为从上面的链接中,似乎是唯一的方法。
谢谢!
我明白了!所以'jane'基本上在giveAllowance之前进行了检查,这就是为什么NameError是在尽管'正确'检查我一直在申请的情况下发生的。确实,字典似乎是可能的出路。我会把关于'家庭'这个名字的建议放在心上。我会找到更好的方式来改善上面的代码。标记为答案。谢谢! – Manhattan