In [4]:
class Animal:
pass
In [6]:
dog1 = Animal()
In [7]:
cat1 = Animal()
In [8]:
isinstance(dog1, Animal)
Out[8]:
In [9]:
isinstance(1, Animal)
Out[9]:
In [10]:
isinstance(1, int)
Out[10]:
In [11]:
class Animal:
def sleep(self):
print "I am sleeping"
def eat(self, food):
print "I am eating" , food
In [12]:
dog1 = Animal()
In [13]:
dog1.sleep()
In [14]:
dog1.eat("an apple")
In [40]:
class Animal:
def __init__(self, name, weight):
self.name = name
self.weight = weight
def sleep(self):
print self.name, "is sleeping"
def eat(self, food):
if self.weight < 10 :
print "I am eating" , food
self.weight += 1
else:
print "no thanks"
In [41]:
dog1 = Animal("doggy" , 1)
In [42]:
dog1.name
Out[42]:
In [43]:
dog1.weight
Out[43]:
In [44]:
dog1.sleep()
In [45]:
dog1.eat("book")
In [38]:
dog1.weight
Out[38]:
In [46]:
cat1 = Animal("kitty" , 1)
In [47]:
cat1.sleep()
In [94]:
class Animal:
def __init__(self, name, weight):
self.name = name
self.__weight__ = weight
def __add__(self, other):
return Animal(self.name+"x"+other.name,
self.__weight__+other.__weight__)
def __repr__(self):
return "My name is "+self.name
def __str__(self):
return "Animal: "+self.name
def sleep(self):
print self.name, "is sleeping"
def eat(self, food):
if self.__weight__ < 10:
print "I am eating", food
self.__weight__ += 1
else:
print "no thanks"
In [95]:
dog1 = Animal("doggy" , 1)
cat1 = Animal("kitty" , 1)
In [96]:
dog1
Out[96]:
In [97]:
print dog1
In [98]:
dog1 + cat1
Out[98]:
In [99]:
dog1.eat(cat1)
In [100]:
class Animal:
def __init__(self, name, weight):
self.name = name
self.__weight__ = weight
def __add__(self, other):
return Animal(self.name+"x"+other.name,
self.__weight__+other.__weight__)
def __repr__(self):
return "My name is "+self.name
def __str__(self):
return "Animal: "+self.name
def sleep(self):
print self.name, "is sleeping"
def eat(self, food):
if self.__weight__ < 10:
print "I am eating", food
self.__weight__ += 1
else:
print "no thanks"
In [111]:
class Bird(Animal):
def __init__(self, name, weight):
Animal.__init__(self, name, weight)
self.name = "!"+self.name+"!"
def fly(self):
print "look", self.name, "is flying"
def __str__(self):
return "Bird: "+self.name
class Fish(Animal):
def swim(self):
print "I am swimming"
def __str__(self):
return "Fish: "+self.name
In [112]:
bird1 = Bird("birdy", 1)
fish1 = Fish("fishy", 1)
In [113]:
bird1 + fish1
Out[113]:
In [114]:
bird1.eat(fish1)
In [115]:
bird1.fly()
In [116]:
fish1.swim()