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

Discussion in 'Python' started by Sandra-24, Apr 21, 2006.

  1. Sandra-24

    Sandra-24 Guest

    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
    Sandra-24, Apr 21, 2006
    #1
    1. Advertising

  2. In article <>,
    "Sandra-24" <> 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.
    Lawrence D'Oliveiro, Apr 22, 2006
    #2
    1. Advertising

  3. Sandra-24

    Cavingdeep Guest

    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__.__subclasses__()[0]()
    Cavingdeep, Apr 22, 2006
    #3
  4. Sandra-24

    Peter Otten Guest

    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
    Peter Otten, Apr 22, 2006
    #4
  5. Sandra-24

    Sandra-24 Guest

    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__.__subclasses__ 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
    Sandra-24, Apr 22, 2006
    #5
  6. In article <>,
    "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.


    That's because you're still thinking in OO terms.
    Lawrence D'Oliveiro, Apr 22, 2006
    #6
  7. Sandra-24

    Peter Otten Guest

    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__.__subclasses__ 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
    Peter Otten, Apr 23, 2006
    #7
  8. Sandra-24

    Sandra-24 Guest

    Lawrence D'Oliveiro wrote:
    > In article <>,
    > "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.

    >
    > 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
    Sandra-24, Apr 23, 2006
    #8
  9. In article <>,
    "Sandra-24" <> 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.
    Lawrence D'Oliveiro, Apr 24, 2006
    #9
  10. Re: Can you create an instance of a subclass with an existing instanceof the base class?

    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 ''.split('@')])"
    bruno at modulix, Apr 24, 2006
    #10
  11. Sandra-24

    Sandra-24 Guest

    Lawrence D'Oliveiro wrote:
    >
    > All you want is a dictionary, then. That's basically what Python objects
    > are.


    Yes, that's it exactly. I made a lazy wrapper for it, and I was really
    happy with what I was able to accomplish, it turned out to be very
    easy.

    Thanks,
    -Sandra
    Sandra-24, Apr 24, 2006
    #11
  12. Re: Can you create an instance of a subclass with an existing instanceof the base class?

    Sandra-24 a écrit :
    > Lawrence D'Oliveiro wrote:
    >
    >>In article <>,
    >> "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.

    >>
    >>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.


    Nope. I mean : they don't overuse OO, they overuse *classes*. AFAIK, OO
    means *object* oriented - not class oriented. There are OO languages
    that don't even have a notion of class.

    > 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.


    Which is a well-known design pattern called "decorator".

    (snip)
    > 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.


    This is OK IMHO.

    > It works, but it has to be redone for every request,


    Is this really a problem ?

    > 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.


    Why copy ? You could as well just use composition/delegation (also using
    __getattr__ - and BTW, this is another possible implementation of the
    decorator pattern).
    Bruno Desthuilliers, Apr 25, 2006
    #12
  13. In article <444cb1e3$0$28592$>,
    bruno at modulix <> wrote:

    >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 ?


    Isn't there one?
    Lawrence D'Oliveiro, Apr 25, 2006
    #13
  14. Re: Can you create an instance of a subclass with an existing instanceof the base class?

    Lawrence D'Oliveiro wrote:
    > In article <444cb1e3$0$28592$>,
    > bruno at modulix <> wrote:
    >
    >
    >>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 ?

    >
    >
    > Isn't there one?


    Your claim that Python "_look_ like an OO language without actually
    being OO" implicitely relies on a definition of OO - or is just
    meaningless. So I ask you: what definition of OO do you use to support
    your claim ?

    --
    bruno desthuilliers
    python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
    p in ''.split('@')])"
    bruno at modulix, Apr 25, 2006
    #14
  15. In article <444d4b92$0$7905$>,
    Bruno Desthuilliers <> wrote:

    >Sandra-24 a écrit :
    >> Lawrence D'Oliveiro wrote:
    >>
    >>>In article <>,
    >>> "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.
    >>>
    >>>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.

    >
    >Nope. I mean : they don't overuse OO, they overuse *classes*. AFAIK, OO
    >means *object* oriented - not class oriented.


    Oh great. Now we have someone redefining the concept of OO to evade the
    point I was making.

    >There are OO languages that don't even have a notion of class.


    Sounds like stuff I was doing in C (a non-OO language) years ago. Unless
    you want to count C as an OO language, I think you're going to have to
    retract this claim.

    >> 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.

    >
    >Which is a well-known design pattern called "decorator".


    If you have to think of it as a design pattern, that means you haven't
    figured out the code reuse angle yet.
    Lawrence D'Oliveiro, Apr 27, 2006
    #15
  16. In article <444e0fff$0$7724$>,
    bruno at modulix <> wrote:

    >Lawrence D'Oliveiro wrote:
    >> In article <444cb1e3$0$28592$>,
    >> bruno at modulix <> wrote:
    >>
    >>
    >>>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 ?

    >>
    >> Isn't there one?

    >
    >Your claim that Python "_look_ like an OO language without actually
    >being OO" implicitely relies on a definition of OO - or is just
    >meaningless.


    Which nicely evades answering the question.
    Lawrence D'Oliveiro, Apr 27, 2006
    #16
  17. Re: Can you create an instance of a subclass with an existing instanceof the base class?

    Lawrence D'Oliveiro wrote:
    > In article <444d4b92$0$7905$>,
    > Bruno Desthuilliers <> wrote:
    >
    >
    >>Sandra-24 a écrit :
    >>
    >>>Lawrence D'Oliveiro wrote:
    >>>
    >>>
    >>>>In article <>,
    >>>>"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.
    >>>>
    >>>>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.

    >>
    >>Nope. I mean : they don't overuse OO, they overuse *classes*. AFAIK, OO
    >>means *object* oriented - not class oriented.

    >
    >
    > Oh great. Now we have someone redefining the concept of OO to evade the
    > point I was making.


    "redefining" ? lol...

    >
    >>There are OO languages that don't even have a notion of class.

    >
    >
    > Sounds like stuff I was doing in C (a non-OO language) years ago. Unless
    > you want to count C as an OO language, I think you're going to have to
    > retract this claim.


    I think I'm not going to retract anything. And I think you should learn
    a bit more about prototype-based languages.

    >
    >>>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.

    >>
    >>Which is a well-known design pattern called "decorator".

    >
    > If you have to think of it as a design pattern, that means you haven't
    > figured out the code reuse angle yet.


    Please stop saying non-sense and learn the difference between design and
    implementation.

    --
    bruno desthuilliers
    python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
    p in ''.split('@')])"
    bruno at modulix, Apr 27, 2006
    #17
  18. In <>, Lawrence D'Oliveiro wrote:

    > In article <444d4b92$0$7905$>,
    > Bruno Desthuilliers <> wrote:
    >
    >>Nope. I mean : they don't overuse OO, they overuse *classes*. AFAIK, OO
    >>means *object* oriented - not class oriented.

    >
    > Oh great. Now we have someone redefining the concept of OO to evade the
    > point I was making.
    >
    >>There are OO languages that don't even have a notion of class.

    >
    > Sounds like stuff I was doing in C (a non-OO language) years ago. Unless
    > you want to count C as an OO language, I think you're going to have to
    > retract this claim.


    That sounds like stuff you do in a language that has objects but no
    classes. As C has no objects I would not count it as an OO language. But
    I count Io as an OO language::

    #!/usr/bin/env io
    Foo := Object clone
    Foo value := 42
    Foo setValue := method(newValue, self value = newValue; self)
    Foo beep := method("beep" linePrint)
    Foo asString := method("I'm a Foo. My value is " .. self value)

    Bar := Foo clone
    Bar asString := method("I'm a Bar and " .. super asString)

    foo := Foo clone
    foo beep
    foo asString linePrint

    bar := Bar clone setValue(23)
    bar beep
    bar asString linePrint

    Output is:

    beep
    I'm a Foo. My value is 42
    beep
    I'm a Bar and I'm a Foo. My value is 23

    That's OO IMHO. Clonable objects that know their "ancestors" so you can
    build an object hierarchy. Missing attributes are looked up in the
    "ancestors" and one can explicitly look up the inheritance tree with
    ``super``. There are no classes, just four objects. Convention in naming
    and usage makes two of them something like templates or "classes" for new
    objects but they are in no way special.

    Ciao,
    Marc 'BlackJack' Rintsch
    Marc 'BlackJack' Rintsch, Apr 28, 2006
    #18
  19. Sandra-24

    Steve Holden Guest

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

    Lawrence D'Oliveiro wrote:
    > In article <444e0fff$0$7724$>,
    > bruno at modulix <> wrote:
    >
    >
    >>Lawrence D'Oliveiro wrote:
    >>
    >>>In article <444cb1e3$0$28592$>,
    >>> bruno at modulix <> wrote:
    >>>
    >>>
    >>>
    >>>>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 ?
    >>>
    >>>Isn't there one?

    >>
    >>Your claim that Python "_look_ like an OO language without actually
    >>being OO" implicitely relies on a definition of OO - or is just
    >>meaningless.

    >
    >
    > Which nicely evades answering the question.


    Well I have to say you are also nicely evading answering the question,
    which is enough to make me suspect your are trolling (deliberately
    asking contentious questions for the purposes of creating futile
    argument and discussion).

    If you *aren't* trolling then what's your objection to saying what led
    you to make the assertion that Python could look like an OO language
    without being one?

    But sine you say later that "Python objects are basically dictionaries"
    it's clear your understanding of Python isn't terribly complete, which
    might cast doubt on your understanding of object orientation.

    For the record, Python *is* an object-oriented language, but it happens
    to offer convenient features for procedural programming as well. Since
    these features are orthogonal to its OO features, the fact that they
    exist doesn't stop Python from being an OO language.

    So why do you assert that it "merely looks like" one?

    regards
    Steve
    --
    Steve Holden +44 150 684 7255 +1 800 494 3119
    Holden Web LLC/Ltd http://www.holdenweb.com
    Love me, love my blog http://holdenweb.blogspot.com
    Recent Ramblings http://del.icio.us/steve.holden
    Steve Holden, Apr 29, 2006
    #19
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. jstorta
    Replies:
    3
    Views:
    431
    jstorta
    Feb 20, 2006
  2. Sridhar R
    Replies:
    14
    Views:
    1,382
    =?iso-8859-1?Q?Fran=E7ois?= Pinard
    Feb 10, 2004
  3. Gerry Sutton
    Replies:
    1
    Views:
    528
    Peter Otten
    Apr 16, 2005
  4. Lou Pecora
    Replies:
    8
    Views:
    330
    Lou Pecora
    May 25, 2006
  5. Trans
    Replies:
    8
    Views:
    310
    Robert Klemme
    Oct 23, 2008
Loading...

Share This Page