473,948 Members | 2,895 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Unpythonic? Impossible??

Assume having this class hierarchy: (in principle and without details)
class A(object):
class B1(A):
class B2(A):
class C1(A1):
class C2(A1):
class C3(B1):
class C4(B2):

each of those classes have an initializer __init__(self, data): and an
overloaded __new__(cls, data):

is it then possible to have this call:
obj = A(data)
return an instance of that particular class (e.g. class C3) in the
hierarchy that - as decided by the __new__ functions - is the 'correct' one?

A.__new__ could select between A, B1 and B2, while B1.__new__ could choose
from B1, C3 and C4.

I know how to use a class factory - and could work around using such a
mechanism. However I am interested to know if I could let the classes do the
work by themselves.

/BJ
Mar 19 '06 #1
7 1149
BrJohan wrote:
Assume having this class hierarchy: (in principle and without details)
class A(object):
class B1(A):
class B2(A):
...
each of those classes have an initializer __init__(self, data): and an
overloaded __new__(cls, data):

is it then possible to have this call:
obj = A(data)
return an instance of that particular class (e.g. class C3) in the
hierarchy that - as decided by the __new__ functions - is the 'correct' one?

A.__new__ could select between A, B1 and B2, while B1.__new__ could choose
from B1, C3 and C4.

I know how to use a class factory - and could work around using such a
mechanism. However I am interested to know if I could let the classes do the
work by themselves.


Yes, it can be done. Yes, it is unclear (and hence UnPythonic).
The class factory _is_ the straightforward way to do this. The
following is the workaround (if you have to maintain A(...)):
class A(object):
def __new__(class_, *args, **kwargs):
if class_ is A:
if want_a_B1(*args , **kwargs):
return B1(*args, **kwargs)
elif want_a_B2(*args , **kwargs):
return B2(*args, **kwargs)
return object.__new__( class_) # Use *a,... except for object

class B1(A):
def __new__(class_, *args, **kwargs):
if class_ is B1:
if want_a_B1(*args , **kwargs):
return B1(*args, **kwargs)
elif want_a_B2(*args , **kwargs):
return B2(*args, **kwargs)
return super(B1, class_).__new__ (class_, *args, **kwargs)
--Scott David Daniels
sc***********@a cm.org
Mar 19 '06 #2
Em Dom, 2006-03-19 Ã*s 08:54 -0800, Scott David Daniels escreveu:
class A(object):
def __new__(class_, *args, **kwargs):
if class_ is A:
if want_a_B1(*args , **kwargs):
return B1(*args, **kwargs)
elif want_a_B2(*args , **kwargs):
return B2(*args, **kwargs)
return object.__new__( class_) # Use *a,... except for object

class B1(A):
def __new__(class_, *args, **kwargs):
if class_ is B1:
if want_a_B1(*args , **kwargs):
return B1(*args, **kwargs)
elif want_a_B2(*args , **kwargs):
return B2(*args, **kwargs)
return super(B1, class_).__new__ (class_, *args, **kwargs)


Why you have that if on B1.__new__? B1 will be created only by
A.__new__, which already did a check.

--
Felipe.

Mar 19 '06 #3

"Scott David Daniels" <sc***********@ acm.org> skrev i meddelandet
news:44******** @nntp0.pdx.net. ..
BrJohan wrote:

....
is it then possible to have this call:
obj = A(data)
return an instance of that particular class (e.g. class C3) in the
hierarchy that - as decided by the __new__ functions - is the 'correct'
one?

A.__new__ could select between A, B1 and B2, while B1.__new__ could
choose from B1, C3 and C4.

I know how to use a class factory - and could work around using such a
mechanism. However I am interested to know if I could let the classes do
the work by themselves.


Yes, it can be done. Yes, it is unclear (and hence UnPythonic).
The class factory _is_ the straightforward way to do this. The
following is the workaround (if you have to maintain A(...)):
class A(object):
def __new__(class_, *args, **kwargs):
if class_ is A:
if want_a_B1(*args , **kwargs):
return B1(*args, **kwargs)
elif want_a_B2(*args , **kwargs):
return B2(*args, **kwargs)
return object.__new__( class_) # Use *a,... except for object

class B1(A):
def __new__(class_, *args, **kwargs):
if class_ is B1:
if want_a_B1(*args , **kwargs):
return B1(*args, **kwargs)
elif want_a_B2(*args , **kwargs):
return B2(*args, **kwargs)
return super(B1, class_).__new__ (class_, *args, **kwargs)
--Scott David Daniels
sc***********@a cm.org


Agreed that the class factory method most often (maybe always) is the best
one. For certain reasons, and in this particular case, I prefer the
UnPythonic way. Sometimes it's good to have "more than one way to do it".

It was the "return object.__new__( class_) " that I did not came to think of
myself, that did it. Thank you for yor helpfulness.

BrJohan
Mar 19 '06 #4
Felipe Almeida Lessa wrote:
Em Dom, 2006-03-19 Ã*s 08:54 -0800, Scott David Daniels escreveu:
class A(object):
def __new__(class_, *args, **kwargs):
if class_ is A:
if want_a_B1(*args , **kwargs):
return B1(*args, **kwargs)
elif want_a_B2(*args , **kwargs):
return B2(*args, **kwargs)
return object.__new__( class_) # Use *a,... except for object

class B1(A):
def __new__(class_, *args, **kwargs):
if class_ is B1:
if want_a_B1(*args , **kwargs):
return B1(*args, **kwargs)
elif want_a_B2(*args , **kwargs):
return B2(*args, **kwargs)
return super(B1, class_).__new__ (class_, *args, **kwargs)


Why you have that if on B1.__new__? B1 will be created only by
A.__new__, which already did a check.


Of course your are right. It needs to be more like:
class B1(A):
def __new__(class_, *args, **kwargs):
if class_ is B1:
if want_a_C1(*args , **kwargs):
return C1(*args, **kwargs)
elif want_a_C2(*args , **kwargs):
return C1(*args, **kwargs)
return super(B1, class_).__new__ (class_, *args, **kwargs)
--Scott David Daniels
sc***********@a cm.org
Mar 19 '06 #5
BrJohan wrote:
I know how to use a class factory - and could work around using such a
mechanism. However I am interested to know if I could let the classes do the
work by themselves.


You can, but a class factory is going to be much clearer and probably
more maintainable. From the user's perspective, there's no difference
from calling a class A to instantiate it, and calling a factory function
called A that selects the appropriate class and returns an instance of it.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
Never had very much to say / Laugh last, laugh longest
-- Des'ree
Mar 19 '06 #6
Erik Max Francis <ma*@alcyone.co m> writes:
You can, but a class factory is going to be much clearer and probably
more maintainable. From the user's perspective, there's no difference
from calling a class A to instantiate it, and calling a factory
function called A that selects the appropriate class and returns an
instance of it.


I remember having a similar problem involving multiple base classes
and deciding that factory functions couldn't do quite what I wanted.
Here's a thread about it, with a recipe using metaclasses by Roeland
Rengelink:

http://tinyurl.com/rz6ne

Unfortunately, the subtleties of what I was trying to do now escape
me.
Mar 19 '06 #7
Paul Rubin wrote:
I remember having a similar problem involving multiple base classes
and deciding that factory functions couldn't do quite what I wanted.
Here's a thread about it, with a recipe using metaclasses by Roeland
Rengelink:

http://tinyurl.com/rz6ne

Unfortunately, the subtleties of what I was trying to do now escape
me.


Your objection seemed to be that you'd prefer that you not have to have
an explicit if/elif... (or lookup table) since that didn't seem very OO.
Any solution that accomplishes this, whether it's a factory function,
metaclasses, or a more traditional type of "virtual constructor" (your
proposal at the end of your post, which is likely how you'd do it in
C++) all need this.

The short version of all this is all these approaches will work, are
Functionally equivalent from the user's perspective, and all require
upkeep, but some require more upkeep than others. In a dynamic language
like Python, the best solution is the most straightforward one that
requires the least upkeep. And that's a factory pattern.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
Man is a hating rather than a loving animal.
-- Rebecca West
Mar 19 '06 #8

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

Similar topics

0
2229
by: erwan | last post by:
It seesm impossible to use the java extension on Mac OS X due to the 'special' file locations of the Java JDK in OS X... am I right ? if not, where can I get some good info or feedback on it ? I am using Mac OS X (10.2.8 with Java 1.4.1) and PHP 4.3.3 there is a standard package to install 4.3.3 but --with-java is not configured in it.... I tried to reconfigure with the standard Java installation on OS X no way...
383
12431
by: John Bailo | last post by:
The war of the OSes was won a long time ago. Unix has always been, and will continue to be, the Server OS in the form of Linux. Microsoft struggled mightily to win that battle -- creating a poor man's DBMS, a broken email server and various other /application/ servers to try and crack the Internet and IS markets. In the case where they didn't spend their own money to get companies to
4
1457
by: Piotre Ugrumov | last post by:
I have tried to modify my exercise about the simulation of the life in the savannah. Now I have only 2 errors but I don't comprehend how resolve these errors. If I try to call the method getX() and getY() of the class Animale from the class Leone, the compiler return to me the same errors. These are the errors: c:\Documents and Settings\Angelo\Documenti\Visual Studio Projects\Savana\Leone.cpp(36) : error C2248: "Animale::x": impossible to...
0
1342
by: Paolino | last post by:
I had always been negative on the boldeness of python on insisting that unbound methods should have been applied only to its im_class instances. Anyway this time I mixed in rightly, so I post this for comments. ###### looking for a discovery .Start ################# class _Mixin(object): def __init__(self,main,instance,*args,**kwargs): # do mixin businnes main.__reinit__(self,instance) # the caveated interface
27
1940
by: Greg Smith | last post by:
Hello, I have been given a programming task that falls into the "impossible" category with my current skill set. I am hoping somebody out there knows how to do this and can save my b-t. I work for a large University. I wrote a Windows-based database application for my department that is used in purchasing. The University has just released Web-base application that does the same thing using a sub set of the data that my application...
0
1056
by: Gianluca | last post by:
Is is true that it's impossible to write a C# wrapper for an IDispatch COM object that has more than one property with parameters? I tried everything I could think of and nothing works. You can only use the this indexer for one parametrized parameter. If this is true, anyone knows if this limitation has been lifted in 2.0? It also appears to be a bug in the proxy that marshals calls to the COM interface is unable to call...
2
1206
by: Cat | last post by:
I created a web site, and I thought I followed XHTML 1.1 rules. But when I validated the pages, I got some error messages. I found that those codes are automatically generated parts by ASP.NET. There is no attribute "name". <form name="form1" method="post" action="Default.aspx" id="form1"> And input is not allowed here Since ASP.NET buttons should be placed in server side forms, I don't know how to remove this error. So, what this...
3
1725
by: Prometheum | last post by:
Having read over some of the disscussions involving incrementing variable names in C++, I have the impression that it's impossible. Is that true? I have a very definite need for them in the following program, and an array won't work. I need to read over a file and store certain information in a struct (person dave; dave.money=200 etc.). However, to stay true to the spec I shouldn't assume that there will always be x many entries I need to store....
9
2630
by: Gabriel | last post by:
Hello, I installed SQL server 2005 SP1 on a Windows XP SP2 From Visual Studio, I'm trygin to create a connection to a database, but I receive this error but I'm creating the connection (I don't receive the database list in the dropdown) "An error has occured while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that
0
9987
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,...
1
11353
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
10694
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
9897
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
8256
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
7431
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
6337
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4949
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
3545
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.