下面的主題已被檢查代替我的問題。使用普通測試來檢查實例是否存在
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