4

I'm new in Python programming with a strong background in Objective-C and Swift. One of the cool thing I love in Swift is the Protocol Oriented Programming with default implementation. I would like to know if it's possible to have the same behaviour in Python?

I'm not sure if it would be a good solution because POP solve problems of the single inheritance but in python we can use multiple inheritance. The thing is that I've heard since the beginning of my programming journey that the multiple inheritance is bad.

From what I think to do is to:

  • Use a abstract class
  • Implement some method of this abstract class
  • Make a class inherit from the abstract class

So I'm curious to know if people use POP in Python? And if yes how they do it?

DEADBEEF
  • 1,930
  • 2
  • 17
  • 32
  • 1
    There is no straightforward translation of Swift's protocol semantics into anything that Python has to offer. If subclassing and multiple inheritance doesn't suffice for your purposes, you can look into some [metaclass-magic](https://stackoverflow.com/questions/13646245/is-it-possible-to-make-abstract-classes-in-python#13646263), though generally speaking that is more likely going to be an overly convoluted approach than not. – Marcel Tesch Apr 09 '18 at 11:58
  • 3
    Switching between Swift and Python myself, I understand your motivation to carry over the protocol oriented model, but in the end it doesn't make much sense to force a certain design pattern onto a language where other more idiomatic approaches exist. – Marcel Tesch Apr 09 '18 at 11:58
  • @MarcelTesch Thanks for your comment and I'm glad you understand my concerns. I totally agree with you that it's a good idea to force a certain design pattern, but I was curious if something in Python already exists. I used but without any success for the moment for different issues I'm trying to solve. But you would recommend multiple inheritance in Python? Isn't it dangerous? – DEADBEEF Apr 09 '18 at 12:17
  • 1
    I'd go with a tentative "yes" for multiple inheritance, it can of course be a powerful tool. It's the kind of thing that gives you enough rope to hang yourself, but by following a couple of best practices and not being overzealous one can build amazing things. Learning about [method resolution order](http://python-history.blogspot.de/2010/06/method-resolution-order.html) is probably the best starting point. – Marcel Tesch Apr 09 '18 at 12:34
  • @MarcelTesch Yeah it's true I love the analogy with the rope ahah. Thank you very much for the really interested article. – DEADBEEF Apr 09 '18 at 12:58

0 Answers0