how to get module globals into a class ?

Peter Otten __peter__ at web.de
Mon Dec 10 04:00:50 EST 2007


stef mientki wrote:

> hello,
> 
> 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.

You can use a hack like

class Base(object):
    def __init__(self):
        module = __import__(self.__module__)
        self.library_color = module.library_color

But I think it's better to add another level to the class hierarchy:

class BrickBase(object):
    def __init__(self):
        self.library_color = self.library_color

class LibraryBase(BrickBase):
    library_color = "blue"

class BrickDoSomethingN(LibraryBase):
    pass

(all untested)

Peter



More information about the Python-list mailing list