How many ways are there to change a variable's value? [closed] - python

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).

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.

How to properly sort/arrange Class Members [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 5 years ago.
Improve this question
I am sure this question was already answered couple of times, and i will soon close this topic, but i couldn't find it.
Is there a recommendet way of arranging member functions?
I am pretty sure not everything need rules, but wanted to if there are thoughts about this topic, which goes more then sorting by access level.
Example class in Pseudocode:
Class
amethod()
bmethod()
cvariable
avariable
bvariable
There are some recommendations, but they are rather vague. The only common point is, quoting the Google Java Style Guide, § 3.4.2,
that each class order its members in some logical order, which its
maintainer could explain if asked. For example, new methods are not just
habitually added to the end of the class, as that would yield "chronological
by date added" ordering, which is not a logical ordering.
The Google C++ Style Guide recommends to order by visibility (which is obvious for C++), then by type:
Typedefs and Enums
Constants (static const data members)
Constructors
Destructor
Methods, including static methods
Data Members (except static const data members)
Oracle’s Code Conventions for Java, § 3.1.3, recommend to order by type, then by visibility (for variables) or functionality (for methods):
Class (static) variables (ordered by visibility)
Instance variables (ordered by visibility)
Constructors
Methods (grouped by functionality rather than by scope or accessibility)
I´m not aware of any generally/widely accepted convention, other than "use something that makes sense" (eg. grouping variables instead of writing a wild mix of vars and functions).
However, it´s not only a style question:
In C++ (and C), the order maps directly to the memory layout, this can lead to different variable sizes because of alignment and padding. Additionally, if serializing something in a binary format, where which value is in the data is of course important (but serializing that way is not exactly good, because the memory layout depends...).
And, like #huu noted in the comments, the variable order determines the initialization order, this is important a member variables is initialized with the value of another member variable (of the same object). A mismatch in variable declaration order and initialization order will lead to a compiler error.

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.

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