The following topics have been checked in lieu of my problem below.
In Python, how do I check if an instance of my class exists?
Python check instances of classes
Bear with me as I am an absolute beginner in Python. I've just started tackling Classes and I decided that a simple family financials emulator is a good starting point for me. Below is my code:
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.
The point of issue is the giveAllowance() function. I have been trying to find a way to check if the target instance of Family exists and to return a transfer of value if it does and a normal string if it doesn't. However, hasattr(), try - except NameError, isinstance(), and even vars()[target] all fail to address the NameError above.
Am I missing something here that I should be doing with respect to classes, ie. an exception when checking for instances from inside another class, wrong syntax, etc? If at all possible, I want to keep away from dictionaries unless they are the last resort, as it seems that from one of the links above, it's the only way.
Thanks!