In [1]:
class Pet(object):
def __init__(self, name, species):
self.name = name
self.species = species
def getName(self):
return self.name
def getSpecies(self):
return self.species
def __str__(self):
return "%s is a %s" % (self.name, self.species)
In [2]:
polly = Pet("Polly", "Parrot")
In [3]:
Pet.getName(polly)
Out[3]:
In [4]:
Pet.getSpecies(polly)
Out[4]:
In [5]:
Pet.getName()
In [6]:
polly.getName()
Out[6]:
In [7]:
polly.getSpecies()
Out[7]:
In [8]:
print polly
In [9]:
ginger = Pet("Ginger", "Cat")
print ginger.getName()
print ginger.getSpecies()
print ginger
In [10]:
clifford = Pet("Clifford", "Dog")
print clifford.getName()
print clifford.getSpecies()
print clifford
In [11]:
class Dog(Pet):
def __init__(self, name, chases_cats):
Pet.__init__(self, name, "Dog")
self.chases_cats = chases_cats
def chasesCats(self):
return self.chases_cats
In [12]:
class Cat(Pet):
def __init__(self, name, hates_dogs):
Pet.__init__(self, name, "Cat")
self.hates_dogs = hates_dogs
def hatesDogs(self):
return self.hates_dogs
In [13]:
mister_pet = Pet("Mister", "Dog")
mister_dog = Dog("Mister", True)
In [14]:
isinstance(mister_pet, Pet)
Out[14]:
In [15]:
isinstance(mister_dog, Pet)
Out[15]:
In [16]:
isinstance(mister_pet, Dog)
Out[16]:
In [17]:
isinstance(mister_dog, Dog)
Out[17]:
In [18]:
mister_dog.chasesCats()
Out[18]:
In [19]:
mister_pet.getName()
Out[19]:
In [20]:
mister_pet.getSpecies()
Out[20]:
In [21]:
mister_dog.getName()
Out[21]:
In [22]:
mister_dog.getSpecies()
Out[22]:
In [23]:
fido = Dog("Fido", True)
rover = Dog("Rover",False)
mittens = Cat("Mittens", True)
fluffy = Cat("Fluffy", False)
In [24]:
print fido
print rover
print mittens
print fluffy
print "%s chases cats: %s" % (fido.getName(), fido.chasesCats())
print "%s chases cats: %s" % (rover.getName(), rover.chasesCats())
print "%s hates dogs: %s" % (mittens.getName(), mittens.hatesDogs())
print "%s hates dogs: %s" % (fluffy.getName(), fluffy.hatesDogs())
Jessica ends here!!!
In [25]:
class Customer(object):
def __init__(self, name, balance=0.0):
self.name = name
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise RuntimeError('No sufficient balance in your account.')
self.balance -= amount
return self.balance
def deposit(self, amount):
self.balance += amount
return self.balance
In [26]:
jeff = Customer('Jeff Knupp', 1000)
In [27]:
jeff.withdraw(100)
Out[27]:
In [28]:
jeff.withdraw(1100)
In [29]:
jeff.deposit(1000)
Out[29]:
In [ ]:
# Same class in a different way
class Customer(object):
def __init__():