I have a question, what is the correct way to define a variable in python3? I mean if it is correct to define it starting with a capital letter, like this:
Capital letter:
self.Var = 1
Variable = 1
OR Lowercase:
self.varInt = 1
variable = 1
And also, what is the correct way to define control variables, StringVar, IntVar, etc?
Is it correct to define it with self.
?
self
it is used only to define class variables, so that they are stored in it. This is a very generic concept of object-oriented programming. So if you doubt about it, look for Python class tutorials.With that code, we could access the variables as follows:
We will see the
prints
cucumbers and potatoes, but bananas will fail. As it is not a variable of the class (because it does not have theself
) bananas, it becomes a temporary variable of the function, that is, it only exists while the function is executed, but it is not saved in the class.Regarding StringVar, IntVar, etc, forget about that in Python. It is an interpreted language where putting
algo = "una string de prueba"
just works. It is not necessary to tell the program what each thing is, unless we specifically want to do very complex things that can be confusing, such as operations with numbersfloat
andintegros
you have to be transforming data, etc.Regarding whether uppercase or lowercase, lowercase and underscore are recommended to separate words. This is seen in the python style standard, PEP8: https://www.python.org/dev/peps/pep-0008/#function-and-variable-names
I do not intervene on self because Saelyth has made it quite clear.
About case sensitivity when initializing a variable:
It is true that being Python an interpreted language there are no rules in this regard, but it is important to have a precise way of doing things and maintain it at all times so that the code is more easily readable by others or by yourself if you need it later. some time.
Here are some examples of how I usually do it:
You can do it the way you like.