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

Michael Spencer mahs at telcopartners.com
Mon Apr 11 15:18:13 EDT 2005


Steven Bethard wrote:
  > 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:
...
> If you need to support old-style classes, replace type(obj) with 
> obj.__class__.
> 
You can use obj.__class__ for both old and new-style classes, so it seems to be 
the safer choice.

Note, that there will be some objects that can't be cloned this way - ('None' 
springs to mind), so you may need to trap TypeError when you call obj.__class__

Michael




More information about the Python-list mailing list