variable scope of class objects

Erik python at lucidity.plus.com
Tue Oct 20 18:17:55 EDT 2015


On 20/10/15 22:33, JonRob at mail.python.org wrote:
> In your comment you mentioned that convention is to declare variables
> (and constants?)  in the construction (__ini__).

I would suggest that 'constants' are not 'declared' in the __init__ 
method body, but either as class variables or (see later) at module scope.

> I am concerned that the sheer number of varialbe / constants would
> make it difficult to read.

Remember that "instance variables" in Python are just name bindings to 
another object which are placed in the object's dictionary.

Python is not like some other languages where you declare your object's 
member variables statically and they all magically exist when you create 
the object (whether you initialise them or not): none of the bindings 
exist until an assignment is executed.

Therefore, you _must_ have a set of assignments which are executed to 
create the object with the bindings (or "instance variables") that you 
require. This is _usually_ done in __init__ with a set of assignments to 
'self' - either using default values or values passed in to __init__.



You may be getting to the point where the best way to structure this is 
to write your own module (rather than just a class) which you then 
import from your main script. For example, you might do something like this:

mymodule.py:

CONSTANT_X = 0x99
CONSTANT_Y = 0xF00
CONSTANT_Z = "Spam"

class MyObject(object):
     def __init__(self, foo, bar):
         # 'foo' can be anything. 'bar' must be one of
         # a specific set of values:
         if bar not in (CONSTANT_X, CONSTANT_Y):
             raise ValueError("Parameter 'bar'")

         self.foo = foo
         self.bar = bar

Then, in your main script you might do something like:

import mymodule

obj = mymodule.MyObject(100, mymodule.CONSTANT_X)

... then start calling methods on 'obj'.

So you just define your address and variable constants at module level 
and import them along with any class and function definitions.

E.



More information about the Python-list mailing list