python - Déterminer le type d'objet

Mots clés : pythondictionarytypestypeofpython

meilleur 4 Réponses python - Déterminer le type d'objet

vote vote

95

>>> type([]) is list True >>> type({}) is dict True >>> type('') is str True >>> type(0) is int True 
>>> class Test1 (object):         pass >>> class Test2 (Test1):         pass >>> a = Test1() >>> b = Test2() >>> type(a) is Test1 True >>> type(b) is Test2 True 
>>> type(b) is Test1 False 
>>> isinstance(b, Test1) True >>> isinstance(b, Test2) True >>> isinstance(a, Test1) True >>> isinstance(a, Test2) False >>> isinstance([], list) True >>> isinstance({}, dict) True 
>>> isinstance([], (tuple, list, set)) True 
vote vote

83

>>> a = [] >>> type(a) <type 'list'> >>> f = () >>> type(f) <type 'tuple'> 
vote vote

76

__class__ 
>>> str = "str" >>> str.__class__ <class 'str'> >>> i = 2 >>> i.__class__ <class 'int'> >>> class Test(): ...     pass ... >>> a = Test() >>> a.__class__ <class '__main__.Test'> 
vote vote

62

>>> obj = object() >>> type(obj) <class 'object'> 
>>> obj.__class__ # avoid this! <class 'object'> 
def foo(obj):     """given a string with items separated by spaces,      or a list or tuple,      do something sensible     """     if isinstance(obj, str):         obj = str.split()     return _foo_handles_only_lists_or_tuples(obj) 
from collections import Iterable from numbers import Number  def bar(obj):     """does something sensible with an iterable of numbers,      or just one number     """     if isinstance(obj, Number): # make it a 1-tuple         obj = (obj,)     if not isinstance(obj, Iterable):         raise TypeError('obj must be either a number or iterable of numbers')     return _bar_sensible_with_iterable(obj) 
def baz(obj):     """given an obj, a dict (or anything with an .items method)      do something sensible with each key-value pair     """     for key, value in obj.items():         _baz_something_sensible(key, value) 

Questions similaires