__new__ to create copy

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Uwe Mayer

    __new__ to create copy

    Hi,

    I want to create a copy of an object from out of its base class:

    class A(object):
    def copy(self):
    ....

    class B(A):
    ....
    [color=blue][color=green][color=darkred]
    >>> b = B()
    >>> b.copy()[/color][/color][/color]

    I'm not sure how to do this:

    def copy(self):
    cpy = self.__new__(se lf.__class__)
    return cpy

    seems not to call the constructor __init__().

    How is such a thing done correctly? Where is the exact difference between
    __new__ and __init__?


    Thanks
    Uwe
  • F. GEIGER

    #2
    Re: __new__ to create copy

    I do object copies this way:

    import copy

    a = A()
    aa = copy.copy(a)

    or

    aa = copy.deepcopy(a )

    You can wrap this up into a method of course, which then can decide whether
    to do a deep copy or not.

    HTH
    Franz GEIGER


    "Uwe Mayer" <merkosh@hadiko .de> schrieb im Newsbeitrag
    news:bvvprg$81b $1@news.rz.uni-karlsruhe.de...[color=blue]
    > Hi,
    >
    > I want to create a copy of an object from out of its base class:
    >
    > class A(object):
    > def copy(self):
    > ...
    >
    > class B(A):
    > ...
    >[color=green][color=darkred]
    > >>> b = B()
    > >>> b.copy()[/color][/color]
    >
    > I'm not sure how to do this:
    >
    > def copy(self):
    > cpy = self.__new__(se lf.__class__)
    > return cpy
    >
    > seems not to call the constructor __init__().
    >
    > How is such a thing done correctly? Where is the exact difference between
    > __new__ and __init__?
    >
    >
    > Thanks
    > Uwe[/color]


    Comment

    • Josiah Carlson

      #3
      Re: __new__ to create copy

      > How is such a thing done correctly? Where is the exact difference between[color=blue]
      > __new__ and __init__?[/color]

      For some reason, I'm not finding the doc page, but I am pretty sure the
      below is the case.
      If __new__ exists, it will be called.
      If __new__ exists, it must call __init__ for __init__ to be called.
      If __new__ doesn't exist, __init__ will be called, if it exists.


      How I usually copy my classes:

      class blah:
      def __init__(self, arg1, arg2, ...):
      self.arg1 = arg1
      self.arg2 = arg2
      ...
      def copy(self):
      return blah(self.arg1, self.arg2, ...)

      It may not be pretty, but it works.

      - Josiah

      Comment

      Working...