473,703 Members | 3,336 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Any gotchas in returning a subclass instance from __new__?

Hi All,

Is anything wrong with the following code?

class Superclass(obje ct):
def __new__(cls):
# Questioning the statement below
return super(Superclas s, cls).__new__(Su bclass)
class Subclass(Superc lass):
pass
if __name__ == '__main__':
instance = Superclass()
print instance

It works here, and even constructors for Subclass and Superclass are
invoked (in correct order), even though such behavior is not explicitly
stated here http://docs.python.org/ref/customization.html. So, am I
asking for trouble or is it /the/ way to go about transforming base
class into a factory?
Thank you,

Sergey.

Aug 1 '06 #1
1 4996
wrote:
Hi All,

Is anything wrong with the following code?

class Superclass(obje ct):
def __new__(cls):
# Questioning the statement below
return super(Superclas s, cls).__new__(Su bclass)
class Subclass(Superc lass):
pass
if __name__ == '__main__':
instance = Superclass()
print instance
The only problems I can think if is that if you create any other subclasses
of Superclass, or of Subclass for that matter then you'll never succeed in
creating any of them, and the constructor i.e. __new__ of the subclass
never gets called.

I've used this technique where the Superclass iterates through all of its
subclasses and uses the constructor parameters to choose the most
appropriate subclass to construct. Eventually though I changed it to use a
separate factory function: that way the __new__ methods get called in the
expected order.

So something like:

@classmethod
def fromMimetype(cl s, m):
for subclass in Superclass._han dlers():
if subclass.suppor tsMimetype(m):
return subclass(m)

@classmethod
def _handlers(cls):
for c in cls.__subclasse s__():
for sub in c._handlers():
yield sub
yield c
It works here, and even constructors for Subclass and Superclass are
invoked (in correct order), even though such behavior is not explicitly
stated here http://docs.python.org/ref/customization.html. So, am I
asking for trouble or is it /the/ way to go about transforming base
class into a factory?
Thank you,
I think you meant the initialisers are invoked correctly (the constructor
is the __new__ method): this isn't suprising since the system simply calls
__init__ on the returned object so the correct thing just happens.

Aug 1 '06 #2

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

Similar topics

2
1543
by: Edward Diener | last post by:
Is there a way in Python to have the constructor of a class "return" another instance of the same class ? I am well aware of the fact that __init__ does not return anything, but I would love to do something like this: class X(object): def __init__(self,...other parameters): # some magic code x = X() y = X()
14
4493
by: Arthur | last post by:
A bit inspired by the decorator discussions, I'm trying to tackle something I had been avoiding. Essentially I am trying to create a non-destructive tranformation of an instance of a class - is one way of putting it. The way I am currently conceptualizing a solution, what I need is a method of the class that returns a new instance of the class. I'm sure this is not new territory.
1
2419
by: Gerry Sutton | last post by:
Hi All! I have noticed a strange behavior when using a constant identifier to initialize an instance list variable in a base class and then trying to modifying the list in subclasses by using either the list.extend method or even by having the subclass create a whole new list in the variable. The following example illustrates the situation.
3
420
by: Larry Lard | last post by:
Hi, This seems to me like a problem that has a simple solution but I can't for the life of me work it out. Suppose I have a base class Employee Public Class Employee Public FullName As String ....
4
1476
by: David Thielen | last post by:
Hi; I am writing a class that implements IDbConnection. The i/f defines a methof BeginTransaction() that returns an IDbTransaction. I want to define this as returning a DbTransaction (as DbConnection does). It makes sense to me that this is legal as DbTransaction implements IDbTransaction so it does meet the contract of returning an IDbTransaction. But it won't compile - how do I get this to work? (There must be a way as DbConnection...
11
1733
by: David Thielen | last post by:
Hi; I am writing a class that implements IDbConnection. The i/f defines a method BeginTransaction() that returns an IDbTransaction. I want to define this as returning a DbTransaction (as DbConnection does). It makes sense to me that this is legal as DbTransaction implements IDbTransaction so it does meet the contract of returning an IDbTransaction. But it won't compile - how do I get this to work? There must be a way as DbConnection...
11
1611
by: Paulo da Silva | last post by:
I would like to implement something like this: class C1: def __init__(self,xxx): if ... : self.foo = foo self.bar = bar else: self=C1.load(xxx)
0
8749
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9243
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
9109
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
9002
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
7853
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
4420
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...
0
4677
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3113
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
2434
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.