鸭子类型在软件开发中意味着什么?
当前回答
“鸭子打字”这个词是一个谎言。
“走路像鸭子,叫起来像鸭子,那就是鸭子”这句俗语在这里一次又一次地被重复着。
但这并不是鸭子打字(或者我们通常所说的鸭子打字)的意思。所有我们正在讨论的鸭子打字,是试图强制命令的东西。看看有什么东西是不是嘎嘎叫,不管它说什么。但是并没有推论出这个物体是不是鸭子。
For true duck typing, see type classes. Now that follows the idiom “If it walks like a duck and quacks like a duck then it is a duck.". With type classes, if a type implements all the methods that are defined by a type class, it can be considered a member of that type class (without having to inherit the type class). So, if there is a type class Duck which defines certain methods (quack and walk-like-duck), anything that implements those same methods can be considered a Duck (without needing to inherit Duck).
其他回答
鸭子打字不是类型提示!
基本上,为了使用“duck typing”,你不会针对特定的类型,而是通过使用公共接口来针对更广泛的子类型(不是谈论继承,当我指的子类型时,我指的是适合相同配置文件的“事物”)。
你可以想象一个存储信息的系统。为了读写信息,你需要某种存储空间和信息。
存储类型可以是:文件、数据库、会话等。
无论存储类型是什么,该接口都会让您知道可用的选项(方法),这意味着在这一点上什么都没有实现!换句话说,接口不知道如何存储信息。
每个存储系统都必须通过实现接口的相同方法来知道接口的存在。
interface StorageInterface
{
public function write(string $key, array $value): bool;
public function read(string $key): array;
}
class File implements StorageInterface
{
public function read(string $key): array {
//reading from a file
}
public function write(string $key, array $value): bool {
//writing in a file implementation
}
}
class Session implements StorageInterface
{
public function read(string $key): array {
//reading from a session
}
public function write(string $key, array $value): bool {
//writing in a session implementation
}
}
class Storage implements StorageInterface
{
private $_storage = null;
function __construct(StorageInterface $storage) {
$this->_storage = $storage;
}
public function read(string $key): array {
return $this->_storage->read($key);
}
public function write(string $key, array $value): bool {
return ($this->_storage->write($key, $value)) ? true : false;
}
}
所以现在,每次你需要写/读信息时:
$file = new Storage(new File());
$file->write('filename', ['information'] );
echo $file->read('filename');
$session = new Storage(new Session());
$session->write('filename', ['information'] );
echo $session->read('filename');
在这个例子中,你最终在存储构造函数中使用Duck Typing:
function __construct(StorageInterface $storage) ...
希望能有所帮助;)
在duck类型中,对象的适用性(例如,在函数中使用)取决于是否实现了某些方法和/或属性,而不是基于该对象的类型。
例如,在Python中,len函数可用于任何实现__len__方法的对象。它并不关心该对象是否属于特定类型,例如字符串、列表、字典或MyAwesomeClass,只要这些对象实现了__len__方法,len将与它们一起工作。
class MyAwesomeClass:
def __init__(self, str):
self.str = str
def __len__(self):
return len(self.str)
class MyNotSoAwesomeClass:
def __init__(self, str):
self.str = str
a = MyAwesomeClass("hey")
print(len(a)) # Prints 3
b = MyNotSoAwesomeClass("hey")
print(len(b)) # Raises a type error, object of type "MyNotSoAwesomeClass" has no len()
换句话说,MyAwesomeClass看起来像鸭子,也像鸭子一样嘎嘎叫,因此是一只鸭子,而MyNotSoAwesomeClass看起来不像鸭子,也不嘎嘎叫,因此不是一只鸭子!
看看语言本身可能会有所帮助;它经常帮助我(我的母语不是英语)。
在鸭子打字中:
1)打字这个词并不是指在键盘上打字(就像我脑海中一直存在的形象那样),而是指确定“那是什么类型的东西?”
2) duck这个词表示决定是如何完成的;这是一种“松散的”定语,比如:“如果它像鸭子一样走路……那它就是一只鸭子。”之所以说“松散”,是因为这个东西可能是一只鸭子,也可能不是,但它是否真的是一只鸭子并不重要;重要的是我能像对待鸭子一样对待它,期待鸭子表现出的行为。我可以喂它面包屑,它可能会向我扑来,向我冲来,或者后退……但它不会像灰熊那样把我吃掉。
Duck typing:
如果它像鸭子一样说话和走路,那么它就是一只鸭子
这通常被称为诱拐(诱拐推理或也称为归纳,我认为一个更清晰的定义):
从C(结论,我们所看到的)和R(规则,我们所知道的),我们接受/决定/假设P(前提,属性),换句话说,一个给定的事实 ... 医学诊断的基础 和鸭子:C =走路,说话,R =像鸭子,P =它是一只鸭子
回到编程:
对象o有方法/属性mp1和接口/类型T 要求/定义mp1 对象o有方法/属性mp2,接口/类型T要求/定义mp2 ...
因此,不仅仅是简单地接受mp1…在任何对象上,只要它满足mp1的某些定义…,编译器/运行时也应该接受断言o是类型T
上面的例子是这样的吗?Duck输入实质上就是没有输入吗?或者我们应该称之为隐式类型?
马特·达蒙解释了《心灵捕手》中的鸭子打字
笔录如下:这里有视频链接。
好吧,我们会有问题吗?
克拉克:没问题。我只是希望你能告诉我鸭子打字到底是什么?我的观点是,鸭系没有很好的定义,也不强
WILL: [interrupting] …and neither is strong typing. Of course that's your contention. You're a first year grad student: you just got finished reading some article on duck typing, probably on StackOverflow, and you’re gonna be convinced of that until next month when you get to the Gang of Four, and then you’re gonna be talking about how Google Go and Ocaml are statistically typed languages with structural sub-tying construction. That's going to last until next year, till you're probably gonna be in here regurgitating Matz, talkin’ about, you know, the Pre-Ruby 3.0 utopia and the memory allocating effects of sub-typing on the GC.
克拉克:(吓了一跳)事实上我不会,因为马茨大大低估了——的影响
WILL:“Matz极大地低估了Ruby 3.0的GC对性能的影响。你是从Donald Knuth的《计算机编程艺术》第98页学到的,对吧?是的,我也读过。你打算为我们剽窃整篇文章吗——你对这件事有什么想法吗?或者,这是你的做法吗,你进入堆栈溢出,你读了r/ruby上一些晦涩的段落,然后你假装,你把它当作你自己的——你自己的想法,只是为了取悦一些女孩,让我的朋友难堪?
[克拉克惊呆了]
威尔:像你这样的人最可悲的是,50年后你会开始自己思考,你会发现生活中有三件事是肯定的。第一,不要那样做。第二,如果它走路像鸭子,那它就是鸭子。第三,你花了十五万美元接受本·科西本可以零美分就能得到的教育。
克拉克:是的,但我会有学位,而你会在我们去滑雪的路上,在汽车餐厅给我的孩子们提供一些廉价的html。
威尔:(微笑)也许吧。但至少我不会没有创意。
(打)
威尔:你遇到了(代码的出现)问题?我想我们可以出去谈谈。
克拉克:没问题
一段时间后:
威尔:你喜欢苹果吗?
克拉克说,嗯?
威尔:你觉得这些苹果怎么样?(砰:威尔把一封信重重地贴在窗户上。)我要谷歌的报价!(出示克拉克的录取通知书,上面有他的面试答案:一张鸭子走路、说话、表现得像一只……鹅)。
不必再说
最后。
(这是对旧答案的一个脚注:)