473,785 Members | 2,466 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question: Inheritance from a buil-in type

Hi there,

A simple but important question:

How can I initialize a super class (like dict) correctly in my subclass constructor?

A sample:

class MyClass(dict):
def __init__(self):
dict.__init__(s elf)
...
Is there a general rule to do this for all buil-in types?

Thanks for help.

Thomas
Jul 18 '05 #1
4 9658
"T. Kaufmann" <me****@snafu.d e> wrote in news:3F******** ******@snafu.de :
A simple but important question:

How can I initialize a super class (like dict) correctly in my
subclass constructor?

A sample:

class MyClass(dict):
def __init__(self):
dict.__init__(s elf)
...
Is there a general rule to do this for all buil-in types?


There are two rules. Generally, immutable objects get their initial values
from the constructor (__new__) while mutable objects are constructed with a
default value (e.g. empty list or dict) and are then set by the initialiser
(__init__) method. A few types which you might expect to be immutable are
actually mutable (e.g. property).

Mutable example (use for list, dict, property, etc.):

class MyClass(dict):
def __init__(self, *args, **kw):
dict.__init__(s elf, *args, **kw)

Immutable example (use for tuple, int, etc.):

class MyClass(tuple):
def __new__(cls, *args, **kw):
return tuple.__new__(c ls, *args, **kw)

If there is any chance of your class being subclassed with multiple
inheritance involved, you should consider using super instead of naming the
baseclass directly, but most of the time you can get away with a direct
call to the baseclass.

--
Duncan Booth du****@rcp.co.u k
int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
"\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #2
T. Kaufmann wrote:
Hi there,

A simple but important question:

How can I initialize a super class (like dict) correctly in my subclass
constructor?
Generally, you also want to override __new__ -- not in all cases can
you do all you want in __init__ by itself (e.g., it's far too late
when you inherit from immutable types, such as numbers, str, tuple).

A sample:

class MyClass(dict):
def __init__(self):
dict.__init__(s elf)
...
Yeah, you can do this, but the dict.__init__ call with just the
self parameter is actually redundant (it wouldn't be if there
WERE arguments -- either keyword ones, or a sequence of pairs,
or both -- with which to actually initialize a non-empty dict...).

Is there a general rule to do this for all buil-in types?


Generally, the super built-in may be advisable if you think you
may ever be involved in a multiple-inheritance graph. But that
is no different whether built-in types are involved, or not. I'm
not sure what "general rule" may be different for built-in types
than for others -- offhand, I don't think there are such differences.
Alex

Jul 18 '05 #3
Duncan Booth <du****@NOSPAMr cp.co.uk> wrote in message news:<Xn******* *************** *****@127.0.0.1 >...

There are two rules. Generally, immutable objects get their initial values
from the constructor (__new__) while mutable objects are constructed with a
default value (e.g. empty list or dict) and are then set by the initialiser
(__init__) method. A few types which you might expect to be immutable are
actually mutable (e.g. property).


What is the thinking behind that? I mean you /can/ pass initial values
to a mutable using __new__, eg

class MyList (list) :
def __new__(cls, *args, **kwargs) :
return list.__new__(cl s, *args, **kwargs)

or __init__ to pass values to a newly created immutable, eg

class MyTuple (tuple) :
def __init__(self, *args, **kwargs) :
return super(tuple, self).__init__( *args, **kwargs)

can't you? What's the pitfall?
Jul 18 '05 #4
af*****@yahoo.c o.uk (Asun Friere) wrote in
news:38******** *************** ***@posting.goo gle.com:
Duncan Booth <du****@NOSPAMr cp.co.uk> wrote in message
news:<Xn******* *************** *****@127.0.0.1 >...

There are two rules. Generally, immutable objects get their initial
values from the constructor (__new__) while mutable objects are
constructed with a default value (e.g. empty list or dict) and are
then set by the initialiser (__init__) method. A few types which you
might expect to be immutable are actually mutable (e.g. property).


What is the thinking behind that? I mean you /can/ pass initial values
to a mutable using __new__, eg

class MyList (list) :
def __new__(cls, *args, **kwargs) :
return list.__new__(cl s, *args, **kwargs)

or __init__ to pass values to a newly created immutable, eg

class MyTuple (tuple) :
def __init__(self, *args, **kwargs) :
return super(tuple, self).__init__( *args, **kwargs)

can't you? What's the pitfall?

The pitfall is that these aren't doing what you think. In both cases you
just passed the original arguments straight through, so the list also got
the arguments it expected in its __init__ method, and the tuple got its
expected arguments in __new__. If you modify the arguments in any way
you'll find that your code still only sees the original arguments.

list.__init__ and tuple.__new__ act on their arguments.
list.__new__ and tuple.__init__ ignore their arguments.

Take the tuple example. tuple() takes 0 or 1 arguments, so you can't write:

tuple(1, 2, 3)

So define a class to do this:
class MyTuple(tuple): def __new__(cls, *args):
return tuple.__new__(c ls, args)

MyTuple(1, 2, 3) (1, 2, 3)

Now try this with __init__ and the default __new__ will complain:
class MyTuple(tuple): def __init__(self, *args):
tuple.__init__( self, args)

MyTuple(1, 2, 3) Traceback (most recent call last):
File "<pyshell#7 3>", line 1, in ?
MyTuple(1, 2, 3)
TypeError: tuple() takes at most 1 argument (3 given)
If you try subclassing list, then this example shows clearly that the
arguments to __new__ are actually ignored:
class MyList (list) : def __new__(cls, *args, **kwargs) :
return list.__new__(cl s, *args, **kwargs)
def __init__(self, *args, **kwargs):
print "list before init",self
list.__init__(s elf, *args, **kwargs)

print MyList([1, 2, 3])

list before init []
[1, 2, 3]
--
Duncan Booth du****@rcp.co.u k
int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
"\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #5

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

Similar topics

17
1829
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
1204
by: JustSomeGuy | last post by:
I have a few classes... class a : std::list<baseclass> { int keya; }; class b : std::list<a> { int keyb;
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.
3
1324
by: Luis Diego Fallas | last post by:
Hi everyone , I'm having a problem when trying to compile code that contains the following pattern: using System; public class A { public class B : Inn.C { }
12
2845
by: Meya-awe | last post by:
I am puzzled, what is the purpose of an interface? How does it work, what i mean is how does the compiler treats this? Why when we talk about separating user interface from business logic, an interface is declared, what is it's purpose? thanks, BRAMOIN *** Sent via Developersdex http://www.developersdex.com ***
6
1263
by: relient | last post by:
Hi, I have three classes: Animal, Dog and Cat. Dog inherits from Animal and Cat inherits from Dog. My question is: is Cat now also a Animal even though it didn't inherit directly from Animal?
14
1500
by: petermichaux | last post by:
Hi, Hopefully the group doesn't mind an(other) inheritance question. Maybe the prototype inheritance style is starting to become a low dim light in my brain...probably not yet. ---- If I do the following...
2
1394
by: mike | last post by:
Hello fellow C++ experts, is there any dramatic difference between multiple inheritance: struct MyType4 : MyType1, MyType2, MyType3 { int MyInt; }; and: struct MyType4 {
13
1468
by: barcaroller | last post by:
What is the common way/design-pattern (if any) in C++ for delegating function calls that are not handled by a certain class. Public inheritance would be one way but not all classes are meant to inherit from (e.g. STL). Example: class A {
4
1627
by: sip.address | last post by:
Hi there, When creating interfaces and implementations, the usual thing is doing somethign like class Interface { public: virtual void f() = 0; virtual void g() = 0; };
0
9485
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
10356
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
10161
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...
0
9958
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
8986
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...
1
7506
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
6743
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
5523
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2890
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.