Python equivalence of default in C#
Is there a way in python to get a types default value?
//C#
default(typeof(int))
I am looking for a more pythonic way to get type defaults?
#python
if(isinstance(myObj, int):
return 0
elif(isinstance(myObj, dict):
return {}
else:
return None
Obviously I dumbed it down. I am dealing with some abstract things, and when someone asks for an attribute I don't have, I basically check a开发者_JAVA技巧 mapping of key->type and return a default instance with a classic switch.
Just instantiate it:
int() # 0
dict() # {}
list() # []
More detail: there's no explicit concept of a 'default value' in Python. There's just an instance of the class instantiated with the default parameters. Some classes may expect arguments when you instantiate them, in which case there isn't really a default value.
How about:
type(myObj)()
It works for int and dict.
精彩评论