欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python 父类方法中使用不同的子类中的不同类对象

程序员文章站 2024-02-03 17:59:34
1 # coding:utf-8 2 3 4 class Animal(object): 5 def __init__(self): 6 self._name = None 7 self._f = None 8 9 def eat(self): 10 print("%s吃%s" % (self._n ......
 1 # coding:utf-8
 2 
 3 
 4 class animal(object):
 5     def __init__(self):
 6         self._name = none
 7         self._f = none
 8 
 9     def eat(self):
10         print("%s吃%s" % (self._name, self._f().food()))
11 
12 
13 class dog(animal):
14     def __init__(self):
15         animal.__init__(self)
16         self._f = dogfood
17         self._name = "狗"
18 
19 
20 class dogfood():
21     def food(self):
22         return "狗粮"
23 
24 
25 class cat(animal):
26     def __init__(self):
27         animal.__init__(self)
28         self._name = "猫"
29         self._f = catfood
30 
31 
32 class catfood():
33     def food(self):
34         return "猫粮"
35 
36 
37 dog = dog()
38 dog.eat()
39 cat = cat()
40 cat.eat()

狗吃狗粮
猫吃猫粮

 

 1 # coding:utf-8
 2 
 3 
 4 class catfood():
 5     def food(self, food_name):
 6         self.food_name = food_name
 7 
 8 cf = catfood
 9 
10 cf1 = catfood()
11 cf1.food("鱼")
12 cf2 = catfood()
13 cf2.food("粥")
14 
15 print(cf1.food_name)
16 print(cf2.food_name)


 

 1 # coding:utf-8
 2 
 3 
 4 class catfood():
 5     def food(self, food_name):
 6         self.food_name = food_name
 7 
 8 cf = catfood
 9 
10 cf1 = catfood()
11 cf1.food("鱼")
12 cf2 = catfood()
13 cf2.food("粥")
14 
15 print(catfood)
16 print(cf)
17 print(cf1)

<class '__main__.catfood'>
<class '__main__.catfood'>
<__main__.catfood object at 0x000000000279b320>

 

cf catfood 是类对象

cf1是实例对象