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.
Related
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 3 years ago.
Improve this question
I'm writing a module which only contains functions. Is it good practice to put these inside a class, even if there are no class arguments and the __init__ function is pointless? And if so how should I write it?
There's no particular reason to force functions to go inside a class if there's no reason to make a class. A python sourcefile already provide a perfectly reasonable namespace for storing similar, related functions. The pypy implementation of the python programming language, for example, has many modules that don't have classes in them (for example, time).
You would want a certain data structure as a class, of course, but there are certain behaviors that are entirely independent of data structures, and putting them in a class would just add needless complexity.
It is good to build modules that contain a class for better organization and manipulation depending on how big the code is and how it will be used, but yes it is good to get use to building classes with methods in them. Can you post your code?
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Do you always have to use __init__ as constructor?
How many constructors can you use it in one class?
Do you need to have 'self' as first argument or you can use any other name like 'shapes' instead of 'self'?
The constructor is optional. However, if you specify one, it must be named __init__; it cannot be named anything else (otherwise, how would Python know which function is the constructor?).
One, called __init__ (though it can call out to other functions).
No, but using a name other than self will make your code harder to read by others, who expect the name self by convention.
The one and only constructor for initializing an instance is __init__. If you want polymorphism, you simply have to be flexible about the way you parse and interpret __init__'s input arguments. Do you have to use it? No, you can omit it, in which case Python calls the __init__ method of the superclass, if any.
There is also a method called __new__, called before __init__, but it is intended for a different purpose and behaves differently: see https://stackoverflow.com/a/674369/3019689
And no, self can be renamed but the result will be less-readable, less-maintainable code since self is the well-established conventional name.
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.
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 9 years ago.
Improve this question
I have python file that has a user interface, that mainly create objects of some class.
That file will be used by my colleagues, on their own computers.
In another file, from my computer, I'm willing to reach those objects that the first file generated.
What will be the best way to "save" the objects of the class, and then reach them from
my computer?
Thanks
What you want to do is have the script serialize the objects, and send them to your computer over the network.
As inspectorG4dget has said, you can use the pickle module to serialize your objects, and the requests library should be good for sending the objects from the client side.
On your machine, you would need a web-server/socket-listener, listening for the sent messages. You would deserialize them, and use them in some way after that.
Pickle or cPickle nicely handles saving object instances (as well as anything else); documentation here.
Two notes from when I fumbled through the a similar problem:
When you load a pickled object instance, you must have the object's class definition present in the namespace of the script/environment where you load.
Not everything can be pickled; I ran into this when saving objects that contained scipy spline instances. In your class definition, you can override the default behavior when pickling and unpickling in order to safely save and restore such attributes.
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 4 years ago.
Improve this question
In Python, if some methods of a class need a helper function, but the helper function itself doesn't use anything in the class, should I put the helper function inside or outside the class?
I tried putting it inside but PyLint was complaining that this function could have been put outside.
#Karl:
The class is a software upgrader and the helper function creates a new folder if the folder doesn't exist yet. The class is in a module having pretty much only the code for the class as of now. Other classes may be added later on.
When deciding where to put helper functions the question I ask is, "Is it only for this class?" If it can help in other places, then it goes at the module level; if it is indeed only for this class, then it goes in the class with either staticmethod (needs no class data to do its job) or classmethod (uses some class, but not instance, data to do its job).
Another python code checker is pyflakes.
It's possible that the helper function better fits in at the module level rather than the class.
If you don't agree that this is the case, there is a staticmethod decorator that you can use on functions inside of the class. Simply put, a static method behaves the same between object instantiations of the same class. It does not rely on instance data.
For this reason, the staticmethod decorator renders behavior on the function such that it does not take an implicit first argument (typically self) as stated in the documentation).