Do OO design principles apply to Python?

2020-05-13 03:09发布

It seems like many OO discussions use Java or C# as examples (e.g. Head First Design Patterns).

Do these patterns apply equally to Python? Or if I follow the design patterns, will I just end up writing Java in Python (which apparently is a very bad thing)?

标签: python oop
10条回答
走好不送
2楼-- · 2020-05-13 03:48

The biggest differences are that Python is duck typed, meaning that you won't need to plan out class hierarchies in as much detail as in Java, and has first class functions. The strategy pattern, for example, becomes much simpler and more obvious when you can just pass a function in, rather than having to make interfaces, etc. just to simulate higher order functions. More generally, Python has syntactic sugar for a lot of common design patterns, such as the iterator and the aforementioned strategy. It might be useful to understand these patterns (I've read Head First and found it pretty useful), but think about Pythonic ways to implement them rather than just doing things the same way you would in Java.

查看更多
ゆ 、 Hurt°
3楼-- · 2020-05-13 03:50

On further thought, some patterns, such as Borg, may be more specific to Python (though similar things can be said about other patterns and languages).

The iterator pattern is also used in Python, albeit in a slightly different form.

Duncan Booth has written an article on patterns in python.

查看更多
我想做一个坏孩纸
4楼-- · 2020-05-13 03:55

It depends on the pattern. Some things are difficult to do in Python: Singleton is an example. You replace this pattern with another, such as, in the case of Singleton, Borg.
It's not insane to use design patterns in Python-- the Iterator pattern, for instance, is integrated into the syntax. However, many things simply aren't done as OO- or pattern-heavy stuff. Python is made to be procedural or functional when it best suits the task, and OO too.
Overall, I'd just say to use your best judgment. If it seems like using Design Pattern Alpha-Gamma is overkill and overcomplication, then it probably is. If it seems like the pattern is perfect for what you want, it probably is.

查看更多
戒情不戒烟
5楼-- · 2020-05-13 04:00

I'd say they apply to Python once you're already doing object-oriented programming with Python. Keep in mind that Python can do a lot more than OOP, and you should use common sense in choosing the appropriate paradigm for the job. If you decide that your program is best represented as a collection of objects, then sure, go ahead and use the design patterns, but don't be afraid to do something completely different if it's called for.

查看更多
家丑人穷心不美
6楼-- · 2020-05-13 04:00

yes, of course they apply. But as noted above, many patterns are built into the language, or made irrelevant by higher level features of the language.

查看更多
7楼-- · 2020-05-13 04:03

Design patterns are little more than duct-tape to fix a languages deficiencies.

查看更多
登录 后发表回答