how to get module globals into a class ?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Dec 10 00:53:58 EST 2007


En Sun, 09 Dec 2007 20:53:38 -0300, stef mientki <stef.mientki at gmail.com>  
escribió:

> this question may look a little weird,
> but I want to create library shells that are a simple as possible.
>
> So I've a module where one base class is defined,
> which looks like this (and might be complex)
>
> base_class_file.py
>     class brick_base ( object ) :
>         ....
>
> now I've a lot of library files,
> in each library file are a lot of classes,
> and each library-file, has some specific parameters, like  
> "library_color",
> so something like this:
>
> library_file.py
>     library_color = ...
>
>     class brick_do_something1( brick_base ) :
>         init :
>             self.Library_Color = Library_Color
>             ....
>
>     class brick_do_something2( brick_base ) :
>         init :
>             self.Library_Color = Library_Color
>             ....
>
> Now this works fine, ...
> ... but the statement "self.Library_Color = Library_Color"
> is completely redundant, because it should be in every class of every
> librray file.
> So I would like to move this statement to the base-class-file,
> but I can't figure out how to accomplish that.

Ok, let's see if I understand your question. Classes defined in  
library_file.py have some attributes in common (like library_color). Other  
classes defined in other files (but also inheriting from brick_base)  
don't. You can use an intermediate class to hold all the common attributes:

library_file.py

     class Library(brick_base):
         library_color = WHITE

     class brick_do_something1(Library):
         ....

     class brick_do_something2(Library):
         ....

Note that I don't even wrote an __init__ method; using a class attribute  
serves as a default instance attribute (until you actually assign  
something to the instance).

x = brick_do_something2()
print x.library_color # prints WHITE

-- 
Gabriel Genellina




More information about the Python-list mailing list