473,748 Members | 4,065 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 5001
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
4495
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
2422
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
1478
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
1736
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
1615
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
9366
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
9316
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
9241
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
8239
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
6793
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
6073
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
3303
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
2777
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2211
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.