473,568 Members | 2,762 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can you create an instance of a subclass with an existing instance of the base class?

Can you create an instance of a subclass using an existing instance of
the base class?

Such things would be impossible in some languages or very difficult in
others. I wonder if this can be done in python, without copying the
base class instance, which in my case is a very expensive object.

Any ideas?

Thanks,
-Sandra

Apr 21 '06 #1
18 7372
In article <11************ **********@j33g 2000cwa.googleg roups.com>,
"Sandra-24" <sa***********@ yahoo.com> wrote:
Can you create an instance of a subclass using an existing instance of
the base class?


I think you're taking Python's OO-ness too seriously. One of the
strengths of Python is that it can _look_ like an OO language without
actually being OO.
Apr 21 '06 #2
With new-style classes you can find out a class' subclasses and then
you can instantiate the subclass you want. Suppose you have two classes
A and B, B is a subclass of A, A is a new-style class. Now you have an
A's instance called "a", to instance B you can do the following:

b = a.__class__.__s ubclasses__()[0]()

Apr 22 '06 #3
Sandra-24 wrote:
Can you create an instance of a subclass using an existing instance of
the base class?

Such things would be impossible in some languages or very difficult in
others. I wonder if this can be done in python, without copying the
base class instance, which in my case is a very expensive object.


You can change the class of an instance by assigning to the __class__
attribute. The new class doesn't even need to be a subclass of the old:
class A(object): .... def __init__(self, name):
.... self.name = name
.... def show(self): print self.name
.... a = A("alpha")
a.show() alpha class B(object): .... def show(self): print self.name.upper ()
.... a.__class__ = B
a.show()

ALPHA

Peter
Apr 22 '06 #4
Now that is a clever little trick. I never would have guessed you can
assign to __class__, Python always surprises me in it's sheer
flexibility.

In this case it doesn't work.

TypeError: __class__ assignment: only for heap types

I suspect that's because this object begins its life in C code.

The technique of using the __class__.__sub classes__ also fails:

TypeError: cannot create 'B' instances

This seems more complex than I thought. Can one do this for an object
that beings it's life in C?

Thanks,
-Sandra

Peter Otten wrote:
Sandra-24 wrote:
Can you create an instance of a subclass using an existing instance of
the base class?

Such things would be impossible in some languages or very difficult in
others. I wonder if this can be done in python, without copying the
base class instance, which in my case is a very expensive object.


You can change the class of an instance by assigning to the __class__
attribute. The new class doesn't even need to be a subclass of the old:
class A(object): ... def __init__(self, name):
... self.name = name
... def show(self): print self.name
... a = A("alpha")
a.show() alpha class B(object): ... def show(self): print self.name.upper ()
... a.__class__ = B
a.show()

ALPHA

Peter


Apr 22 '06 #5
In article <11************ *********@v46g2 000cwv.googlegr oups.com>,
"Sandra-24" <sa***********@ yahoo.com> wrote:
Now that is a clever little trick. I never would have guessed you can
assign to __class__, Python always surprises me in it's sheer
flexibility.


That's because you're still thinking in OO terms.
Apr 22 '06 #6
Sandra-24 wrote:
Now that is a clever little trick. I never would have guessed you can
assign to __class__, Python always surprises me in it's sheer
flexibility.

In this case it doesn't work.

TypeError: __class__ assignment: only for heap types

I suspect that's because this object begins its life in C code.

The technique of using the __class__.__sub classes__ also fails:

TypeError: cannot create 'B' instances

This seems more complex than I thought. Can one do this for an object
that beings it's life in C?


The restriction originates in the metaclass. Perhaps you can use a
customized metaclass that allows subclass assignment, but I don't know
enough about Python's internals to tell you how/whether that is possible.

An alternative might be that you always start out with a subclass coded in
Python:
abc = tuple("abc")
abc.__class__ = tuple Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: __class__ assignment: only for heap types

class Tuple(tuple): pass .... class Subclass(Tuple) : .... first = property(lambda self: self[0])
.... abc = Tuple("abc")
abc.__class__ = Subclass
abc.first

'a'

In the example a Tuple should be able to do everything a tuple can do;
because Tuple is coded in Python you can also change the __class__.

Peter

Apr 23 '06 #7
Lawrence D'Oliveiro wrote:
In article <11************ *********@v46g2 000cwv.googlegr oups.com>,
"Sandra-24" <sa***********@ yahoo.com> wrote:
Now that is a clever little trick. I never would have guessed you can
assign to __class__, Python always surprises me in it's sheer
flexibility.


That's because you're still thinking in OO terms.


It's not quite as simple as all that. I agree that people, escpecially
people with a Java (ew) background overuse OO, when there's often
simpler ways of doing things.

However in this case I'm simply getting an object (an mp_request object
from mod_python) passed into my function, and before I pass it on to
the functions that make up and individual web page it is modified by
adding members and methods to add functionality. It's not that I'm
thinking in OO, but that the object is a convienient place to put
things, especially functions that take an mp_request object as their
first argument.

Sadly I'm unable to create it as a python object first, because it's
created by the time my code comes into play. So I have to resort to
using the new module to add methods.

It works, but it has to be redone for every request, I thought moving
the extra functionality to another object would simplify the task. A
better way might be to contain the mp_request within another object and
use __getattr__ to lazily copy the inner object. I'd probably have to
first copy those few fields that are not read-only or use __setattr__
as well.

Thanks,
-Sandra

Apr 23 '06 #8
In article <11************ *********@v46g2 000cwv.googlegr oups.com>,
"Sandra-24" <sa***********@ yahoo.com> wrote:
However in this case I'm simply getting an object (an mp_request object
from mod_python) passed into my function, and before I pass it on to
the functions that make up and individual web page it is modified by
adding members and methods to add functionality.


All you want is a dictionary, then. That's basically what Python objects
are.
Apr 24 '06 #9
Lawrence D'Oliveiro wrote:
(snip)
I think you're taking Python's OO-ness too seriously. One of the
strengths of Python is that it can _look_ like an OO language without
actually being OO.


According to which definition of OO ?

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Apr 24 '06 #10

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

Similar topics

0
1236
by: Stephen Nesbitt | last post by:
All: Here's my implementation problem. I have a base class which has the responsibility for providing entry into the logging system. Part of the class responsibility is to ensure that lagger names are consistent. For all intents and purposes this class should be considered abstract and will always be subclassed. What I want to do is the...
37
2804
by: Mike Meng | last post by:
hi all, I'm a newbie Python programmer with a C++ brain inside. I have a lightweight framework in which I design a base class and expect user to extend. In other part of the framework, I heavily use the instance of this base class (or its children class). How can I ensure the instance IS-A base class instance, since Python is a fully dynamic...
4
1636
by: Joe HM | last post by:
Hello - I have a Base Class where I want a New() implemented that can be called from the outside. This New() should create an instance of the appropriate cDerivedX Class ... The following shows a scenario where it was determined that cDerivedA is needed based on a configuration file. Dim lInstance As New cBase()
8
1663
by: Lou Pecora | last post by:
I've been scanning Python in a Nutshell, but this seems to be either undoable or so subtle that I don't know how to do it. I want to subclass a base class that is returned from a Standard Library function (particularly, subclass file which is returned from open). I would add some extra functionality and keep the base functions, too. But I...
1
4988
by: s.lipnevich | last post by:
Hi All, Is anything wrong with the following code? class Superclass(object): def __new__(cls): # Questioning the statement below return super(Superclass, cls).__new__(Subclass) class Subclass(Superclass): pass
5
3160
by: JH | last post by:
Hi I found that a type/class are both a subclass and a instance of base type "object". It conflicts to my understanding that: 1.) a type/class object is created from class statement 2.) a instance is created by "calling" a class object.
5
4464
by: Sergio Montero | last post by:
I have a MustInherits Base class that implements a custom IDataLayer interfase. IDataLayer expose CRUD methods. Base class constructor requires two parameters: ConnectionString TableName Another assembly, sharing the root namespace, contains a set of Custom attributes used to validate properties values, just like the Validation...
6
4572
by: Me | last post by:
I need to be able to acces non-virtual members of sublcasses via a base class pointer...and without the need for an explicit type cast. I thought a pure virtual getPtr() that acts as a type cast would solve the problem, but it appears not to. I need this functionality to make object serialization a reality. Having to explicitly cast each...
4
3471
by: Kurt Smith | last post by:
Hi List: Class inheritance noob here. For context, I have the following base class and subclass: class Base(object): def __init__(self, val): self.val = val
0
7604
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...
0
7916
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. ...
0
8117
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...
1
7660
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...
0
7962
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...
0
6275
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...
1
5498
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...
0
5217
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...
0
3631
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.