#1.145——152节课25章——面向对象三大特性小案例
class Animal:
def __init__(self,name,age=1):
self.name = name
self.age = age def eat(self):
print("%s在吃饭" % self) def play(self):
print("%s在玩" % self) def sleep(self):
print("%s在睡觉" % self)
class Person(Animal):
def __init__(self,name,pets,age):
super(Person,self).__init__(name,age)
self.pets = pets def yang_pets(self):
for pet in self.pets:
pet.eat()
pet.play()
pet.sleep()
def make_pets_work(self):
for pet in self.pets:
# if isinstance(pet,Dog):
# pet.watch()
# elif isinstance(pet,Cat):
# pet.catch()
pet.work() def __str__(self):
return "名字是{},年龄{}岁的人".format(self.name,self.age)
# p = Person("sz",[1,2],18)
# print(p.__dict__)
class Cat(Animal): def work(self):
print("%s在捉老鼠" % self) def __str__(self):
return "名字是{},年龄{}岁的小猫".format(self.name,self.age) class Dog(Animal): def work(self):
print("%s在看家" % self) def __str__(self):
return "名字是{},年龄{}岁的小狗".format(self.name,self.age) d = Dog("小黑",18)
c = Cat("小红",2)
p = Person("sz",[d,c],18)
p.yang_pets() p.make_pets_work() #2.第15章
class Caculator:
def __check_num_zsq(func):
def inner(self,n):
if not isinstance(n,int):
raise TypeError("当前这个数据的类型有问题,应该是一个整型数据")
return func(self,n)
return inner @__check_num_zsq
def __init__(self,num):
self.__result = num @__check_num_zsq
def jia(self, n):
self.__result += n @__check_num_zsq
def jian(self, n):
self.__result -= n def cheng(self, n):
self.__result *= n def show(self):
print("计算的结果是:%d" % self.__result) c1 = Caculator(2)
c1.jia(6)
c1.jian(4)
c1.cheng(5)
c1.show()