Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python have C#/Java-style interfaces?

Tags:

python

oop

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 python (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?

like image 368
samb8s Avatar asked Sep 27 '11 16:09

samb8s


3 Answers

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.

like image 92
S.Lott Avatar answered Sep 21 '22 06:09

S.Lott


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!

like image 38
andronikus Avatar answered Sep 21 '22 06:09

andronikus


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

like image 38
Schildmeijer Avatar answered Sep 20 '22 06:09

Schildmeijer