Do OO design principles apply to Python?

后端 未结 10 856
伪装坚强ぢ
伪装坚强ぢ 2021-01-30 11:19

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 pat

相关标签:
10条回答
  • 2021-01-30 11:56

    The use of Java or C# is probably due to the mainstream popularity of the language.

    But design principle and/or design patterns apply irrespective of the language you use. The implementation of the same design pattern in Python would obviously be different than in Java or C#.

    0 讨论(0)
  • 2021-01-30 11:58

    Python has it's own design idioms. Some of the standard patterns apply, others don't. Something like strategy or factories have in-language support that make them transparent.

    For instance, with first-class types anything can be a factory. There's no need for a factory type, you can use the class directly to construct any object you want.

    Basically, Python has its own design idioms that are somewhat different largely because it's so dynamic and has incredible introspection capabilities.

    Example:

    x = list
    my_list = x(range(0,5)) #creates a new list by invoking list's constructor
    

    By assigning the class-type to a callable object you can essentially remove any 'factory' types in your code. You are only left with callables that produce objects that should conform to some given conventions.

    Furthermore, there are design patterns in Python that just can't be represented in other statically-typed languages efficiently. Metaclasses and function decorators are good examples of this.

    0 讨论(0)
  • 2021-01-30 12:06

    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.

    0 讨论(0)
  • 2021-01-30 12:11

    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.

    0 讨论(0)
提交回复
热议问题