Creating a new instance of a class by what is sent in?

Discussion in 'Python' started by ChinStrap, Apr 11, 2005.

  1. ChinStrap

    ChinStrap Guest

    I am sorry if this is obvious, but I am not seeing it. How would I go
    about creating a new type that is of the same type as a class sent into
    the function?

    new = foo.__init__() refers to the current foo, not a new fresh
    instance of my class. The only way I can think of is to make a large
    if-elif chain of isinstances, but that loses the generality I am after.

    Thank you for your help.
    ChinStrap, Apr 11, 2005
    #1
    1. Advertising

  2. ChinStrap wrote:
    > I am sorry if this is obvious, but I am not seeing it. How would I go
    > about creating a new type that is of the same type as a class sent into
    > the function?
    >
    > new = foo.__init__() refers to the current foo, not a new fresh
    > instance of my class. The only way I can think of is to make a large
    > if-elif chain of isinstances, but that loses the generality I am after.


    It looks like you want to create a new _instance_ of the same type as an
    _instance_ passed in to a function. If this is correct, you can do this by:

    py> def new(obj):
    .... return type(obj)()
    ....
    py> new('s')
    ''
    py> new(3)
    0
    py> new(['a', 'b'])
    []
    py> new((5.3, 3j))
    ()

    If you need to support old-style classes, replace type(obj) with
    obj.__class__.

    If this is not the question you meant to ask, could you reword things?
    Creating a new _type_ that is the same _type_ as something else doesn't
    make much sense to me. If it's a new _type_, then it shouldn't be the
    same as any existing type.

    STeVe
    Steven Bethard, Apr 11, 2005
    #2
    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. Sridhar R
    Replies:
    14
    Views:
    1,398
    =?iso-8859-1?Q?Fran=E7ois?= Pinard
    Feb 10, 2004
  2. Damo
    Replies:
    5
    Views:
    459
    trippy
    Nov 16, 2006
  3. Martin P. Hellwig
    Replies:
    1
    Views:
    374
    Martin P. Hellwig
    Mar 26, 2010
  4. Olive
    Replies:
    4
    Views:
    241
    Olive
    Jul 6, 2012
  5. Ugur
    Replies:
    2
    Views:
    247
Loading...

Share This Page