Do you always have to use __init__ as constructor? [closed] - python

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.

Related

Should modules always contain 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 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?

How many ways are there to change a variable's value? [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 4 years ago.
Improve this question
In Python, if you want to change a variable's value, there are multiple ways:
foo = 1 # By assignment
bar.func() # By calling its method.
for baz in range(5): # By "leaking" from a loop
Just out of curiosity, I want to find every way to achieve this goal in a "normal" program. By "normal" I mean not directly manipulating locals() or do similar things.
Also I know there's some discussion around whether Python has real "variable", but let's not focus on that for this question.
I'm afraid it's really not clear what "change a variable's value" means to you. Python objects have state, so you can coherently ask which methods may mutate an object's state, and names in Python can be bound to objects, so you can coherently ask how such bindings can change.
For the former, it depends on the type of the object. For the latter, see section 4.2.1 ("Binding of names") in the Python Language Reference Manual:
The following constructs bind names: formal parameters to functions, import statements, class and function definitions (these bind the class or function name in the defining block), and targets that are identifiers if occurring in an assignment, for loop header, or after as in a with statement or except clause. The import statement of the form from ... import * binds all names defined in the imported module, except those beginning with an underscore. This form may only be used at the module level.
A target occurring in a del statement is also considered bound for this purpose (though the actual semantics are to unbind the name).

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.

regarding self in method calls python, couldnt get a specific answer to my query [closed]

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
class downloader(QDialog):
def __init__(self):
QDialog.__init__(self)
Can someone explain why there is a self in the method call? was self to be used only for method definitions and not mandatory for method calls?
If you call x.foo(), then self is added as the first argument only if x is an instance of a class (making foo a bound function). However, if x is itself a class, the function is unbounded and no parameter will be added.
In your case, QDialog is a class, so it does not add self automatically, thus the need to add it manually.
Instance methods always receive an implicit first argument. You can call it whatever you want, but usually the word "self" is used (just like the word "this" is used in similar contexts of other languages)

Python - Should I put my helper functions inside or outside the 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 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).

Categories

Resources