473,748 Members | 7,590 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

multiple inheritance

Hi.

I think I'm missing something about multiple inheritance in python.

I've got this code.

class Foo:
def __init__(self):
self.x = "defined by foo"
self.foo = None

class Bar:
def __init__(self):
self.x = "defined by bar"
self.bar = None

class Foobar(Foo,Bar) :
pass

fb = Foobar()
print fb.x
print fb.__dict__

which returns :
defined by foo
{'x': 'defined by foo', 'foo': None}

So I guess not defining __init__ in my class Foobar will call __init__
from my superclass Foo. Also __dict__ doesn't show an attribute
'bar':None so I guess Bar.__init__ is not called at all.

I would like to have a subclass with all attributes from superclasses
defined, and only the attribute from the first when there is conflict
(i.e. in this case, Foobar would be like this but with bar:None)

I tried this :

class Foobar(Foo,Bar) :
def __init__(self):
Foo.__init__(se lf)
Bar.__init__(se lf)

defined by bar
{'x': 'defined by bar', 'foo': None, 'bar': None}

Here I have all I want, except the value of 'x' comes from the 'Bar'
superclass rather than Foo. So, to have what I want, I would have to
invert the two calls to __init__ in order to have the right x value.

What I find awkward here is that the order of __init__ calls matters,
rather than the order of the classes in the class declaration.

Do you have any ideas of a way to get this multiple inheritance thing
solved without having to do those __init__ calls ?

Thomas

Feb 15 '06 #1
5 2824

Thomas Girod a écrit :
Hi.

I think I'm missing something about multiple inheritance in python.

I've got this code.

class Foo:
def __init__(self):
self.x = "defined by foo"
self.foo = None

class Bar:
def __init__(self):
self.x = "defined by bar"
self.bar = None

class Foobar(Foo,Bar) :
pass

fb = Foobar()
print fb.x
print fb.__dict__

which returns :
defined by foo
{'x': 'defined by foo', 'foo': None}

So I guess not defining __init__ in my class Foobar will call __init__
from my superclass Foo. Also __dict__ doesn't show an attribute
'bar':None so I guess Bar.__init__ is not called at all.

I would like to have a subclass with all attributes from superclasses
defined, and only the attribute from the first when there is conflict
(i.e. in this case, Foobar would be like this but with bar:None)

I tried this :

class Foobar(Foo,Bar) :
def __init__(self):
Foo.__init__(se lf)
Bar.__init__(se lf)
defined by bar
{'x': 'defined by bar', 'foo': None, 'bar': None}

Here I have all I want, except the value of 'x' comes from the 'Bar'
superclass rather than Foo. So, to have what I want, I would have to
invert the two calls to __init__ in order to have the right x value.

What I find awkward here is that the order of __init__ calls matters,
rather than the order of the classes in the class declaration.

Do you have any ideas of a way to get this multiple inheritance thing
solved without having to do those __init__ calls ?


try:

class Foo(object):
def __init__(self):
super(Foo, self).__init__( ) # not really necessary here
self.x = "defined by foo"

class Bar(object):
def __init__(self):
super(Bar, self).__init__( )
self.x = "defined by bar"

class FooBar(Foo, Bar):
def __init__(self):
super(FooBar, self).__init__( )
and search for the "cooperativ e methods and super" section
in http://www.python.org/2.2/descrintro.html

Cheers,

SB


Thomas


Feb 15 '06 #2
Hi Thomas,

When an object is created, the __init__ function will be called. Since
you didn't define it in Foobar, the search path finds the __init__
function in Foo, so that's the one that is called. The second __init__
in Bar is masked since it comes second in the inheritance list..

If you want to call both constructors, then what you did is fine! The
fact that 'x' comes from the Bar object is ok too. That's what you told
python to do. What did you expect if you are setting 'x' twice? I mean,
when I type the following two statements into the interpreter:

a = 1
a = 2

then after those two statements execute, the value of a is
naturally 2, not 1. Same with your 'x'.

And what is wrong with the explicit calls to each constructor? After
all, in python, explicit is better than implicit. If you don't believe
me,
type "import this" in your interpreter:

import this

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Feb 15 '06 #3
Sébastien Boisgérault <Se************ *******@gmail.c om> wrote:
and search for the "cooperativ e methods and super" section
in http://www.python.org/2.2/descrintro.html


...., then read http://fuhm.org/super-harmful/ (not the evangelism, just
the examples) and
http://mail.python.org/pipermail/pyt...ry/050656.html .

When done, ask yourself if you need cooperative method calling or just
calls to the superclasses' __init__-functions. It's your call then,
because we don't know your use cases.

Cheers,
-jnf
Feb 16 '06 #4
thanks, you pointed exactly on what distrurbed me. I'll see what I can
do with cooperative methods.

Feb 16 '06 #5
That's perfect. thanks.

Feb 16 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
4336
by: Graham Banks | last post by:
Does using multiple inheritance introduce any more performance overhead than single inheritance?
5
2180
by: Morgan Cheng | last post by:
It seems no pattern defined by GoF takes advantage of multiple inheritance. I am wondering if there is a situation where multiple inheritance is a necessary solution. When coding in C++, should multiple inheritance still be avoided? If yes, why multiple inheritance is introducted into C++?
20
10082
by: km | last post by:
Hi all, In the following code why am i not able to access class A's object attribute - 'a' ? I wishto extent class D with all the attributes of its base classes. how do i do that ? thanks in advance for enlightment ... here's the snippet #!/usr/bin/python
22
23383
by: Matthew Louden | last post by:
I want to know why C# doesnt support multiple inheritance? But why we can inherit multiple interfaces instead? I know this is the rule, but I dont understand why. Can anyone give me some concrete examples?
47
3640
by: Mark | last post by:
why doesn't .NET support multiple inheritance? I think it's so silly! Cheers, Mark
60
4930
by: Shawnk | last post by:
Some Sr. colleges and I have had an on going discussion relative to when and if C# will ever support 'true' multiple inheritance. Relevant to this, I wanted to query the C# community (the 'target' programming community herein) to get some community input and verify (or not) the following two statements. Few programmers (3 to7%) UNDERSTAND 'Strategic Functional Migration
15
28374
by: iKiLL | last post by:
hi all, I would like to be able to create an umbrella class for all my main global sections but I would still like to keep them all in separate file something like the below but I keep getting an error saying you are not allowed Multiple base classes. /// <summary>
7
3739
by: Adam Nielsen | last post by:
Hi everyone, I'm having some trouble getting the correct chain of constructors to be called when creating an object at the bottom of a hierarchy. Have a look at the code below - the inheritance goes like this: Shape | +-- Ellipse | +-- Circle
47
4025
by: Larry Smith | last post by:
I just read a blurb in MSDN under the C++ "ref" keyword which states that: "Under the CLR object model, only public single inheritance is supported". Does this mean that no .NET class can ever support multiple inheritance. In C++ for instance I noticed that the compiler flags an error if you use the "ref" keyword on a class with multiple base classes. This supports the above quote. However, under the "CodeClass2.Bases" property (part...
2
2585
by: Paul McGuire | last post by:
On May 25, 8:37 am, Michael Hines <michael.hi...@yale.eduwrote: Here's a more general version of your testing code, to detect *any* diamond multiple inheritance (using your sample classes). -- Paul for cls in (A,B,C,D): seen = set()
0
8831
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9548
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9374
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6796
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6076
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4607
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3315
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2787
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.