Class Inheritance

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Thu Mar 13 04:31:09 EDT 2008


Andrew Rekdal < a écrit :
> I am trying to bring functions to a class by inheritance... for instance in 
> layout_ext I have..
> 
> 
> --- layout_ext.py---------
> class Layout()
>     def...some function that rely on css in Layout.py

It shouldn't, definitively. The Layout instance should have a reference 
on the CSS instance, ie:

# layout_ext.py
class LayoutExt(object):
   def __init__(self, css):
     self.css = css

   def some_function(self):
      do_something_with(self.css)

# layout.py
from layout_ext import LayoutExt
from CSS import CSS

class Layout(LayoutExt):
    def __init__(self, css):
        LayoutExt.__init__(self, css)
        # etc


>     def...
> 
> ---EOF--
> 
> in the main application file I have...
> ----Layout.py---
> from layout_ext import Layout
> from CSS import CSS
> css = CSS()
> class Layout(Layout)

You will have a problem here - this class statement will shadow the 
Layout class imported from layout_ext. Remember that in Python, def and 
class statements are executed at runtime and that they bind names in 
current namespace - here, the 'class Layout' statement rebinds the name 
'Layout' in the Layout module's namespace.


>     def __init__
>     more code.....
> 
> ----EOF----
> 
> 
> Problem is layout_ext and Layout code is dependant on a Class instance 
> 'css'.  Whenever the CSS instance it parses a file, this means that I would
> have to parse the file twice?? Why is this? Can I do something like pass an 
> already created instance to the import?

Wrong solution, obviously. cf above for the most probably correct one.

HTH



More information about the Python-list mailing list