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

C

ChinStrap

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.
 
S

Steven Bethard

ChinStrap said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top