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

Steven Bethard steven.bethard at gmail.com
Mon Apr 11 14:58:09 EDT 2005


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



More information about the Python-list mailing list