variable scope of class objects

JonRob JonRob
Tue Oct 20 17:33:21 EDT 2015



Hello Luca,

I very much appreciated your comments.  And I understand the
importance of "doing something right"  (i.e. convention).

This leads me to another question.

Because I am interfacing with an I2C sensor I have many register
definations to include (30 register addresses and  26 Variables to be
red from some of those registers.
In your comment you mentioned that convention is to declare variables
(and constants?)  in the construction (__ini__).
I am concerned that the sheer number of varialbe / constants would
make it difficult to read.

In your opinion, what would be the best method to structure such code?

Regards
JonRob




On Tue, 20 Oct 2015 08:17:16 +0200, Luca Menegotto
<otlucaDELETE at DELETEyahoo.it> wrote:

>Il 19/10/2015 20:39, JonRob ha scritto:
>
>> I (think) I understand that in the below case, the word self could be
>> replaced with "BME280" to explicitly call out a variable.
>>
>> But even still I don't know how explicit call out effects the scope of
>> a variable.
>
>These two statements make me think you come from C++ or something similar.
>
>In Python you can declare variables at class level, but this declaration 
>must NOT be interpreted in the same manner of a similar declaration in 
>C++: they remain at the abstract level of a class, and they have nothing 
>to do with an instance of a class (in fact, to be correctly invoked, 
>they must be preceeded by the class name).
>
>'self' (or a similar representation, you could use 'this' without 
>problem) gives you access to the instance of the class, even in the 
>constructor; it is important, because the constructor is the place where 
>instance variables should be defined. Something like this:
>
>class foo:
>     # invoke with foo._imAtClassLevel
>     _imAtClassLevel = 10
>
>     def __init__(self):
>         #  need to say how this must be invoked?
>         self._imAtInstanceLevel = 0
>
>no confusion is possible, because:
>
>class foo2:
>     _variable = 1000
>
>     def __init__(self):
>         # let's initialize an instance variable with
>         # a class variable
>         self._variable = foo2._variable
>
>Please, note that declaring a variable in the constructor is only a 
>convention: in Python you can add a variable to an object of a class 
>wherever you want in your code (even if it is very dangerous and 
>discouraged).



More information about the Python-list mailing list