By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,587 Members | 1,665 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,587 IT Pros & Developers. It's quick & easy.

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

P: n/a
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.

Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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
Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.