variable scope of class objects
Luca Menegotto
otlucaDELETE at DELETEyahoo.it
Thu Oct 22 05:59:56 EDT 2015
Maybe I've been too cryptic. I apologize.
Il 22/10/2015 01:35, JonRob ha scritto:
> @Dennis,
>
>
> Thanks for your example. My structure is very similar.
And that's ok. But you can also 'attach' the constants to a class, if it
makes sense. For example, the same code of Dennis can be written as:
class SensorA():
GYROXREG = 0x0010
GYROYREG = 0x0011
GYROZREG = 0x0001
_registers = [GYROXREG, GYROYREG, GYROZREG]
And then you can invoke those constants as:
SensorA.GYROXREG
to emphasize that they are significant to this class, and to this class
only.
> Luca wrote...
>> 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).
This is the cryptic part.
I mean: you can do, and it's perfectly legal:
class A():
def __init__(self):
self.a = 10
if __name__ == '__main__':
o = A()
print(o.a)
# this is a new member, added on the fly
o.b = 20
print(o.b)
but, for God's sake, use it only if you have a gun at your head!
--
Ciao!
Luca
More information about the Python-list
mailing list