[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.python

Union of class variables

Joan Miller

2/16/2010 8:16:00 AM

Is possible to get a third class with the class variables of another
two classes?

--------
class A:
foo = 1

class B:
bar = 2
--------
3 Answers

alex23

2/16/2010 8:40:00 AM

0

On Feb 16, 6:16 pm, Joan Miller <pelok...@gmail.com> wrote:
> Is possible to get a third class with the class variables of another
> two classes?
>
> --------
> class A:
>     foo = 1
>
> class B:
>     bar = 2
> --------

Through multiple inheritance?

>>> class C(A, B):
... pass
...
>>> C.foo
1
>>> C.bar
2

Joan Miller

2/16/2010 8:59:00 AM

0

On 16 feb, 08:40, alex23 <wuwe...@gmail.com> wrote:
> On Feb 16, 6:16 pm, Joan Miller <pelok...@gmail.com> wrote:
>
> > Is possible to get a third class with the class variables of another
> > two classes?
>
> > --------
> > class A:
> >     foo = 1
>
> > class B:
> >     bar = 2
> > --------
>
> Through multiple inheritance?
>
>   >>> class C(A, B):
>   ...   pass
>   ...
>   >>> C.foo
>   1
>   >>> C.bar
>   2

Yes! It solves the problem :) Thanks!

Ben Finney

2/16/2010 9:01:00 AM

0

Joan Miller <peloko45@gmail.com> writes:

> Is possible to get a third class with the class variables of another
> two classes?

Multiple inheritance is allowed in Python:

class Baz(Foo, Bar):
pass

However, it leads to complications that you likely don't want, e.g.
<URL:http://www.artima.com/weblogs/viewpost.jsp?thread=....

Is it *really* the case that the new class is best expressed by an IS-A
relationship to *both* the others? (â??Every Baz IS-A Foo; every Baz IS-A
Bar�)

You should consider composition, instead. Decide which other class
represents the more general case of the new class, and give it
additional capabilities through a HAS-A relationship. (â??Every Baz IS-A
Foo; every Baz HAS-A Bar�)

class Baz(Foo):

def __init__(self):
self.bar = Bar()

That way, you keep the clarity of single inheritance and additional
capabilities are accessed through an attribute.

--
\ â??Always code as if the guy who ends up maintaining your code |
`\ will be a violent psychopath who knows where you live.â? â??John |
_o__) F. Woods |
Ben Finney