Path: csiph.com!eternal-september.org!feeder.eternal-september.org!aioe.org!.POSTED!not-for-mail From: Luca Menegotto Newsgroups: comp.lang.python Subject: Re: variable scope of class objects Date: Thu, 22 Oct 2015 11:59:56 +0200 Organization: Aioe.org NNTP Server Lines: 50 Message-ID: References: <9ocd2btlkq7kp3margtn4sj3mehd7bpimm@4ax.com> <9i7g2b17d3e54cbcf35digbod9216fnovl@4ax.com> NNTP-Posting-Host: jyK346aZFHsQ6PZHWmWRng.user.speranza.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=windows-1252; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Thunderbird/38.3.0 X-Notice: Filtered by postfilter v. 0.8.2 Xref: csiph.com comp.lang.python:97888 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