尝试了一下更负责一点的例子,完全okay,
class Character(object):
def __init__(self):
self.age = 10
def printAge(self):
print self.age
class Human(Character):
def __init__(self, human_name, pet_name, pet_type='dog'):
super(Human,self).__init__()
self.name = human_name
if pet_type == 'dog':
self.pet = Dog(pet_name, human_name)
elif pet_type == 'cat':
self.pet = Cat(pet_name, human_name)
else:
self.pet = Pet(pet_name, human_name)
def __str__(self):
return 'my name is '+self.name
class Pet(object):
def __init__(self,pet_name,human_name):
self.age = 1
self.name = pet_name
self.owner = human_name
def __str__(self):
return 'i am a pet, i belongs to ' + self.owner + ', and my name is ' + self.name
class Dog(Pet):
def __init__(self,pet_name,human_name):
super(Dog,self).__init__(pet_name,human_name)
def __str__(self):
return 'i am a dog, i belongs to ' + self.owner + ', and my name is ' + self.name
class Cat(Pet):
def __init__(self,pet_name,human_name):
super(Cat,self).__init__(pet_name,human_name)
def __str__(self):
return 'i am a cat, i belongs to ' + self.owner + ', and my name is ' + self.name
jack = Human('jack','jenny','dog')
mary = Human('mary','nick','cat')
chris = Human('chris','lua','girlfriend')
print jack
print mary
print chris
print '\n'
print jack.pet
print mary.pet
print chris.pet
感叹一下,python的OOP功能真是厉害! |