简体   繁体   English

Java接口和Python Mixin之间的区别?

[英]Difference between Java Interfaces and Python Mixin?

I have been reading about Python-Mixin and come to know that it adds some features (methods) to class. 我一直在阅读有关Python-Mixin并且知道它为类添加了一些功能(方法)。 Similarly, Java-Interfaces also provide methods to class. 同样, Java-Interfaces也提供了用于分类的方法。

Only difference, I could see is that Java-interfaces are abstract methods and Python-Mixin carry implementation. 我可以看到的唯一区别是Java-interfaces是抽象方法, Python-Mixin带有实现。

Any other differences ? 还有其他区别吗?

Well, the 'abstract methods' part is quite important. 好吧,“抽象方法”部分非常重要。

Java is strongly typed. Java是强类型的。 By specifying the interfaces in the type definition, you use them to construct the signature of the new type. 通过在类型定义中指定接口,可以使用它们来构造新类型的签名。 After the type definition, you have promised that this new type (or some sub-class) will eventually implement all the functions that were defined in the various interfaces you specified. 在类型定义之后,您已承诺此新类型(或某些子类)最终将实现在您指定的各种接口中定义的所有功能。

Therefore, an interface DOES NOT really add any methods to a class, since it doesn't provide a method implementation. 因此,接口实际上不会向类添加任何方法,因为它不提供方法实现。 It just adds to the signature/promise of the class. 它只是增加了类的签名/承诺。

Python, however, is not strongly typed. 但是,Python不是强类型的。 The 'signature' of the type doesn't really matter, since it simply checks at run time whether the method you wish to call is actually present. 类型的“签名”并不重要,因为它仅在运行时检查您要调用的方法是否确实存在。

Therefore, in Python the mixin is indeed about adding methods and functionality to a class. 因此,在Python中,mixin确实是关于向类添加方法和功能的。 It is not at all concerned with the type signature. 它根本与类型签名无关。

In summary: 综上所述:

  • Java Interfaces -> Functions are NOT added, signature IS extended. Java接口->功能未添加,签名已扩展。
  • Python mixins -> Functions ARE added, signature doesn't matter. Python mixins->功能已添加,签名无关紧要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM