程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-05(2)

鸭子类型

发布于2019-10-28 15:34     阅读(1459)     评论(0)     点赞(16)     收藏(4)


鸭子类型


鸭子模式
动态类型语言的一种风格
多态性:向不同对象传递统一信息,不同的对象在接收到信息时,会做出不同反应
接口:标准
在鸭子类型中,不关注对象的类型本身,而是如何使用的

1. 鸭子类型通常不会理会函数参数类型,依赖于文档(告知传递的对象---有对应的方法)
	认为控制
	鸭子类型(过于灵活)
2. 关注的不是类型,只关注方法和属性
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
#只关注方法,不关注对象类型
class Duck:
	def swim(self):
		print('duck swim')
	def quack(self):
		print('duck quack')
	def feather(self):
		print('duck has feather')
class Bird:
	def swim(self):
		print('Bird swim')
	def quack(self):
		print('Bird quack')
	def feather(self):
		print('Bird has feather')
class Human:
	def swim(self):
		print('human like dog swim')
	def quack(self):
		print('human quack')
	def feather(self):
		print('human has feather')
	def eat(self):
		pass
def forest(duck):
	'''有swim quack feather的调用'''
	duck.swim()
	duck.quack()
	duck.feather()
def game():
	d=Duck()
	b=Bird()
	h=Human()
	forest(d)
	forest(b)
	forest(h)
game()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
#结果
duck swim
duck quack
duck has feather
Bird swim
Bird quack
Bird has feather
human like dog swim
human quack
human has feather
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10


所属网站分类: 技术文章 > 博客

作者:放羊人

链接:https://www.pythonheidong.com/blog/article/147024/ea626ab4e4454b11d70b/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

16 0
收藏该文
已收藏

评论内容:(最多支持255个字符)