473,796 Members | 2,460 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A question about inheritance

Hello I have a question about inheritance in Python. I'd like to do
something like this:

class cl1:
def __init__(self):
self.a = 1

class cl2(cl1):
def __init__(self):
self.b = 2

But in such a way that cl2 instances have atributes 'b' AND 'a'.
Obviously, this is not the way of doing it, because the __init__
definition in cl2 overrides cl1's __init__.

Is there a 'pythonic' way of achieving this?

Armando Serrano

Jul 19 '05 #1
3 1420
Thanks.

Jp Calderone wrote:
On 8 May 2005 12:07:58 -0700, ar******@gmail. com wrote:
Hello I have a question about inheritance in Python. I'd like to do
something like this:

class cl1:
def __init__(self):
self.a = 1

class cl2(cl1):
def __init__(self):
self.b = 2

But in such a way that cl2 instances have atributes 'b' AND 'a'.
Obviously, this is not the way of doing it, because the __init__
definition in cl2 overrides cl1's __init__.

Is there a 'pythonic' way of achieving this?


class cl2(cl1):
def __init__(self):
cl1.__init__(se lf)
self.b = 2

Jp


Jul 19 '05 #2
ar******@gmail. com wrote:
Hello I have a question about inheritance in Python. I'd like to do
something like this:

class cl1:
def __init__(self):
self.a = 1

class cl2(cl1):
def __init__(self):
self.b = 2

But in such a way that cl2 instances have atributes 'b' AND 'a'.
Obviously, this is not the way of doing it, because the __init__
definition in cl2 overrides cl1's __init__.

Is there a 'pythonic' way of achieving this?


If there's a chance you might have multiple inheritance at some point in
this hierarchy, you might also try using super:

class cl1(object): # note it's a new-style class
def __init__(self):
self.a = 1

class cl2(cl1):
def __init__(self):
super(cl2, self).__init__( )
self.b = 2

Note that you probably want a new-style class even if you chose not to
use super in favor of Jp Calderone's suggestion. There are very few
cases for using old-style classes these days.

STeVe
Jul 19 '05 #3
Ok, thanks. I didn't know about new-style classes (I had learned python
from a book prior to them).

After reading about new-style classes, I find that your solution is
better because, using super (in general) avoids cl2 from having to know
the implementation details of cl1. This is clearly explained in:

http://www.python.org/2.2.3/descrintro.html#cooperation

Also, when using new-style classes with IDLE, I found some problems
which I talk about in "Modifying CallTips.py to work with with
new-style classes in IDLE.", which I posted in this group.

Steven Bethard wrote:
ar******@gmail. com wrote:
Hello I have a question about inheritance in Python. I'd like to do
something like this:

class cl1:
def __init__(self):
self.a = 1

class cl2(cl1):
def __init__(self):
self.b = 2

But in such a way that cl2 instances have atributes 'b' AND 'a'.
Obviously, this is not the way of doing it, because the __init__
definition in cl2 overrides cl1's __init__.

Is there a 'pythonic' way of achieving this?
If there's a chance you might have multiple inheritance at some point

in this hierarchy, you might also try using super:

class cl1(object): # note it's a new-style class
def __init__(self):
self.a = 1

class cl2(cl1):
def __init__(self):
super(cl2, self).__init__( )
self.b = 2

Note that you probably want a new-style class even if you chose not to use super in favor of Jp Calderone's suggestion. There are very few
cases for using old-style classes these days.

STeVe


Jul 19 '05 #4

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

Similar topics

2
1914
by: Stephan Diehl | last post by:
I have a question about metaclasses: How would be the best way to "merge" different metaclasses? Or, more precisely, what is the best way to merge metaclass functionality? The idea is basicly the following: One has several (metaclass) modules that implements an interesting feature. Lets say, I have a metaclass L, that adds logging capabilities to all method calls and another one, called P, that creates properties on the fly.
17
1830
by: Andrew Koenig | last post by:
Suppose I want to define a class hierarchy that represents expressions, for use in a compiler or something similar. We might imagine various kinds of expressions, classified by their top-level operator (if any). So, an expression might be a primary (which, in turn, might be a variable or a constant), a unary expression (i.e. the result of applying a unary operator to an expression), a binary expression, and so on. If I were solving...
2
1578
by: Tony Johansson | last post by:
Hello Experts!! Here we use multiple inheritance from two classes.We have a class named Person at the very top and below this class we have a Student class and an Employee class at the same level. There is a class TeachingAssistent that use multiple inheritance from both Student and Employee. There is a method named getName is class Person.
1
1817
by: Tony Johansson | last post by:
Hello Experts! I have some questions about inheritance that I want to have an answer to. It says "Abstract superclasses define a behavioral pattern without specifying the implementation" I know that an abstract class doesn't have any implementaion even if a default implementatiion can be supplied for pure virtual methods. What does it actually mean with saying that an Abstract superclasses define a behavioral pattern?
3
1111
by: Quentin Huo | last post by:
Hi: C# doesn't support multiple inheritance but it supports interface.But I think these ways are different. For example, C++ supports multiple inheritance. I have two classess classA and classB: class classA(){ ......
18
1933
by: Tom Cole | last post by:
I'm working on a small Ajax request library to simplify some tasks that I will be taking on shortly. For the most part everything works fine, however I seem to have some issues when running two requests at the same time. The first one stops execution as the second continues. If I place either an alert between the two requests or run the second through a setTimeout of only 1 millisecond, they both work. You can see a working example here:...
14
2155
by: JoeC | last post by:
I have been writing games and I also read about good programming techniques. I tend to create large objects that do lots of things. A good example I have is a unit object. The object controls and holds everything a unit in my game is supposed to do. What are some some cures for this kind of large object or are they OK because they represent one thing. If not what are better ways to design objects that behave the same way. Would it be...
3
2554
by: Jess | last post by:
Hello, I've been reading Effective C++ about multiple inheritance, but I still have a few questions. Can someone give me some help please? First, it is said that if virtual inheritance is used, then "the responsibility for initializing a virtual base is borne by the most derived class in the hierarchy". What does it mean? Initializing base class is usually done automatically by the compiler, but a derived class can invoke the base...
8
4274
by: Tony Johansson | last post by:
Hello! I wonder can somebody explain when is it suitable to use these methods OnKeyUp, OnKeyDown and OnKeyPress because these raise an event. These are located in class UserControl. If these raise an event how do I create an handler to catch these raised events. //Tony
0
9529
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
10457
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
10231
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
10176
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10013
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9054
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6792
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();...
1
4119
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
3
2927
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.