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?
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:
__dict__
(a dictionary of all of an
object's members). MyObj.__dict__.hasKey(o)
is what you want, I think. (pretty easy)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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With