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

--
Ciao!
Luca

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to