[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Class Inheritance

Timothy Adams" <teadams65

3/13/2008 5:07:00 AM

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
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)
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?


-- Andrew


2 Answers

Marc 'BlackJack' Rintsch

3/13/2008 7:54:00 AM

0

On Thu, 13 Mar 2008 00:06:52 -0500, "Andrew Rekdal" < wrote:

> Problem is layout_ext and Layout code is dependant on a Class instance
> 'css'.

Then pass that instance to the `Layout` class in the `__init__()` so both,
the base class and the subclass use the same `CSS` instance.

Ciao,
Marc 'BlackJack'

Bruno Desthuilliers

3/13/2008 8:31:00 AM

0

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