Python inheritance - multiple superclasses [closed] - python

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Is that a pythonic way to create a class that inherits from more than 10 classes? Or maybe I should consider a different approach?

it is allowed, you can also consider creating a composite object, an object that has other objects as it's members, instead of inheriting them.
wiki for the concept of composition: composition
multiple inheritance in python: multiple inheritance
these should help you understand, and then decide what is better for you in the context of your program.

Yes, inheriting from multiple classes in perfectly legal. However, if you have 10 super classes, it seems that you might need to tweak your inheritance tree. Perhaps some of the classes can be inherited by intermediate classes so that the final class inherits from fewer classes.
You should also learn about composition which might provide a cleaner solution for what you are trying to do.

Multiple inheritance is valid in Python but not used often. Most of usecases that I seen is mixins (small snippets mixed into a main heirarchy tree).
Creating a class with 10 parents is a bad smell in any OOP language and not pythonic at all. You should refactor you classes into another kind of abstraction.

Is that OK to inherit from many classes (more than 10) in Python?
It is "OK", in that Python will accept it and will not break or crash.
Is that a pythonic way to create a class or I should consider a different approach?
It is, most certainly, not a "pythonic" way to create a class. Having many parent classes only aggravates the well-known problems of having a few parent classes (diamond problem, etc.), plus it makes the class directly dependent on many others, and makes it very difficult to track down where each behavior in a class comes from. That goes against the general spirit of simplicity in Python (or good programming practices in general).
Note that making a class child of another one establishes an "is a" relationship. Is your class really all of those ten things? Or are you just inheriting to gain some of the already implemented behaviors? Look up some basic principles of object-oriented design such as SOLID, why sometimes we may prefer composition over inheritance, and alternative architectural patterns such as entity–component–system.

Related

Why would I use classmethod constructor in Python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am reading Effective Python by Slatkin. In item 24, he talks about achieving polymorphism in python by using classmethod functions that play the role of constructors.
However, it is not clear to me why this is necessary. Why can we not achieve the same goal by simply using __init__ and overriding it in every derived class, the same way we're overriding the classmethod?
In his case, he has only one constructor per class, so why not use regular init for that purpose rather than classmethod?
You can see what's item 24 here, unfortunately details are missing:
http://ptgmedia.pearsoncmg.com/images/9780134034287/samplepages/9780134034287.pdf
More details here:
http://qiita.com/giwa/items/fd563a93825714cffd70
In the examples given in the book, the classmethod doesn't produce a single element. All different classes support the same classmethod (same signature) but what they do to produce the instances or how many they produce, is delegated to the class.
The PathInputData class, for example, produces inputs based on the config['data_dir'] configuration, using os.listdir() to read the all input files. You can imagine a DatabaseInputData class that provides the same generate_inputs() class method, but instead connects to a database and runs a SQL query. It'll look for different configuration. Etc.
You can't do this with the __init__ method; that's for initialising a single instance. If there are 0 instances to produce of the class, __init__ wouldn't even be called, but it still is a good idea to delegate the responsibility to find out how many instances must be produced to the class.

Structure of a program with many global variables [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
As the title suggests, I'm interested in the best (perhaps the most Pythonic way) to structure a program which uses many global variables.
First of all, by "many", I mean some 30 variables (which may be dictionaries, floats or strings) which every module of my program needs to access. Now, there seem to be two ways to do this:
define the "global" variables in seperate modules
use an object oriented approach
The advantage of using an object oriented approach is that I can have many instances of some main class initialized, and perhaps compare different values (results of some analysis, for example) later on.
I already have a program written, but basically it breaks down to one class with some 30 or so attributes. Although it works fine, I'm aware this is a pretty messy way to do this.
So, basically, is I use OOP approach, I would perhaps need to break my main class down to a few subclasses, every one of which stores specific logically related variables.
Any suggestions are welcome.
P.S. Just to be concrete about what I'm trying to do: I have a FEM-solver which needs to store structure info, element and node data, analysis result data, etc. So, I'm dealing with a lot of data types most of which are connected in some way.
Unfortunately, as was hinted at in the comments, there is no "Pythonic" way to do this. Having a large number of global constants is just fine - many programs and libraries do this. But in the comments, you've specified that all of your globals are being modified.
You need to take your program's architecture back to the drawing board. Rethink the relationships between your program's entities (functions, classes, modules, etc). There has to be a better way to organize it.
And by the way, it also sounds like you're getting close to using the God Object Antipattern. Use some of the advice in this SO question to refactor your massive class that has it's fingers all over your program.

What is the benefit of having a whole program contained in a class? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Sometimes, when looking at Python code examples, I'll come across one where the whole program is contained within its own class, and almost every function of the program is actually a method of that class apart from a 'main' function.
Because it's a fairly new concept to me, I can't easily find an example even though I've seen it before, so I hope someone understands what I am referring to.
I know how classes can be used outside of the rest of a program's functions, but what is the advantage of using them in this way compared with having functions on their own?
Also, can/should a separate module with no function calls be structured using a class in this way?
A module is preferred when it is a collection of pure functions i.e. no shared state like module level variables. A big class is often used when there are multiple functions operating on a shared state.
In Python scripts, you will often see the pattern of the main function being just the instantiation of a class and calling a method for e.g youtube-dl. This is done for various reasons:
Can instantiate multiple objects without mixing state. It is easier to make it threadsafe.
Classes can be inherited or composed (for e.g. see BaseHTTPRequestHandler
Classes have more features than modules like constructors, iteration support etc.
In general, classes offer more power with slight added complexity. Some people prefer functions for simplicity esp in the case of one-time scripts. The tradeoff is upto the developer and both are valid options in Python.
A program often has to maintain state and share resources between functions (command line options, dB connection, etc). When that's the case a class is usually a better solution (wrt/ readability, testability and overall maintainability) than having to pass the whole context to every function or (worse) using global state.

What is the preferred Python 3.x class definition syntax? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
As Is it necessary or useful to inherit from python's object in Python 3.x? and Python class inherits object make clear, it is no longer necessary to inherit from object when defining a class in Python 3.
As a corollary to this which isn't directly addressed by either of the linked questions: should I prefer either style over the other when writing new Python 3 code? Is it better to drop the object base class in the interest of cleaner class definitions, or leave it in in order to (potentially) make future ports to Python 2 easier?
Programming is converting the abstract ideas into a formal form that is later used to produce executable. There is no need to make the process more complex than neccessary. The machines were created to help us. It does not apply in the opposite direction.
In some sense, Python 3 is a new language. Then the question should be: "Should I force myself to use the new language so that it would look the way the old tools/programmers were used to?"
It's time again to read the Zen of Python one by one:
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
pylint appears to still warn about not using object when defining a class in 3.x, so I also add it, even for 3.x-only code. I write a lot of Python that runs on both 2.x and 3.x; there it's a cinch that you want it.
But you make reasonable arguments for both sides, really. What do you think?

Multiple inheritance in python vs composition [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have a solid understanding of OOP and its idioms in Java.
Now I am coding in python, and I am in a situation where having multiple inheritance may be useful, however (and this may be due to years of java code), i am reluctant to do it and I am considering using composition instead of inheritance in order to avoid potential conflicts with potential equal method names.
Question is, am i being to strict or too java focused regarding this thing. Or using multiple inheritance in python is not only possible but also encouraged.
Thanks for your time :)
The question of "inheritance vs. composition" comes down to an attempt to solve the problem of reusable code. You don't want to have duplicated code all over your code, since that's not clean and efficient. Inheritance solves this problem by creating a mechanism for you to have implied features in base classes. Composition solves this by giving you modules and the ability to simply call functions in other classes.
If both solutions solve the problem of reuse, then which one is appropriate in which situations? The answer is incredibly subjective, but I'll give you my three guidelines for when to do which:
Avoid multiple inheritance at all costs, as it's too complex to be useful reliably. If you're stuck with it, then be prepared to know the class hierarchy and spend time finding where everything is coming from.
Use composition to package up code into modules that is used in many different unrelated places and situations.
Use inheritance only when there are clearly related reusable pieces of code that fit under a single common concept, or if you have to because of something you're using.
However, do not be a slave to these rules. The thing to remember about object oriented programming is that it is entirely a social convention programmers have created to package and share code. Because it's a social convention, but one that's codified in Python, you may be forced to avoid these rules because of the people you work with. In that case, find out how they use things and then just adapt to the situation.
More details can be found on: http://learnpythonthehardway.org/book/ex44.html
I would still prefer composition to inheritance, whether multiple or single. Really getting into duck typing is a bit like having loads of implicit interfaces everywhere, so you don't even need inheritance (or abstract classes) very much at all in Python. But that's prefer composition, not never use inheritance. If inheritance (even multiple) is a good fit and composition isn't, then use inheritance.

Categories

Resources