开发者

Does Python have C#/Java-style interfaces?

开发者 https://www.devze.com 2023-04-07 19:50 出处:网络
I worked for a few months as a C# programmer, and got used to the idea of generics/templates interfaces, which I could pass to a library without caring how the object was created.

I worked for a few months as a C# programmer, and got used to the idea of generics/templates interfaces, which I could pass to a library without caring how the object was created.

I'm about to start on a relatively large project, probably in p开发者_C百科ython (I've written a lot of python before, but mostly my own code for data analysis etc), and was wondering if there exists a similar concept in this language? I've tried googling for it and not come up with much.

If the answer's no, that's fine, but in that case what do people generally do instead?


If the answer's no, that's fine, but in that case what do people generally do instead?

Duck Typing.

What's important is to approach Python by dropping the technical baggage of C#.

Learn Python as a new language. Don't try to map concepts between Python and C#. That way lies madness.


"INTERFACES, not generics, or templates"

Doesn't matter. All that static type declaration technology isn't necessary. For that matter type casting in order to break the rules isn't necessary either.


My understanding of interfaces is from Java, so hopefully that's close enough to what you mean...

There is no syntactic way to assert that a particular object has a set of methods and fields because Python uses dynamic typing/duck typing. If you want to check whether an object has a certain method or field, you can:

  • Dig into it with reflection (this is the most work)
  • Check for what you want in its __dict__ (a dictionary of all of an object's members). MyObj.__dict__.hasKey(o) is what you want, I think. (pretty easy)
  • Just use the object and trust that you, your fellow developers, or your users have given you a proper object. (Maximum easy, but dangerous)
  • Or, do the above and wrap it in a try/except block. (This will be familiar to Java programmers)

Designing a complex set of classes in Python is a very different experience from doing the same in C-like languages, so be prepared to do things you may be uncomfortable with (like option 3, above). Good luck!


python is dynamically typed so (in most cases) there is no need for generics/templates.


If you are talking strictly about C#/Java-like interface, then the answer is simple. They are concepts that belong to statically typed languages and do not really apply to dynamic language such as Python.

The usual pythonic approach is to trust the objects you get and assume they have the necessary traits you need. Should they do not, you might expect runtime errors that can be handled or left for the caller. This matches the general dynamic nature of the language: if something goes wrong, you can expect it to surface at runtime.

Interfaces from Java or C#, on the other hand, are means for checking necessary preconditions (i.e. objects having certain methods) during compilation. This (arguably) trades off some of the runtime flexibility for increased safety of compile-time checks.

Note that it doesn't mean that any concept of interface has no place in dynamically typed language. In fact, Python has a slightly blurred notion of "meta-types" - such as iterables - that are often checked against, e.g. by verifying the presence of particular method(s):

def process_sequence(seq):
    if not hasattr(seq, '__iter__'):
        seq = [seq] # turn single element into iterable
    for elem in seq:
        process_element(elem)

This is conceptually similar to non-manifest interfaces from Go language. If you want to have your own iterable, you just implement the __iter__ method - without explicitly stating that you will implement it (as in Java, where you would inherit from List class). Should anyone wants to check whether your object is indeed an iterable, they can verify whether the "contract" - i.e. having __iter__ method - is indeed fulfilled. This is what andronikus described in their answer.

As a shameless plug, I can point out to the pyduck library that I'm implementing. It aims to simplify (and maybe even standarize) verification of such "contracts" (via reflection) and make it slightly more reliable.


zope.interface

But most people don't use it.

0

精彩评论

暂无评论...
验证码 换一张
取 消