python - Obtenir le nom de classe d'une instance

Mots clés : pythonintrospectioninstanceofpython-datamodelpython

meilleur 5 Réponses python - Obtenir le nom de classe d'une instance

vote vote

98

>>> import itertools >>> x = itertools.count(0) >>> type(x).__name__ 'count' 
x.__class__.__name__ 
vote vote

87

instance.__class__.__name__ 
vote vote

71

>>> class A: ...     def whoami(self): ...         print(type(self).__name__) ... >>> >>> class B(A): ...     pass ... >>> >>> >>> o = B() >>> o.whoami() 'B' >>> 
vote vote

64

class A:   pass  a = A() str(a.__class__) 
"{0}.{1}".format(a.__class__.__module__,a.__class__.__name__) 
vote vote

58

type(instance).__name__ != instance.__class__.__name__ # if class A is defined like class A():    ...  type(instance) == instance.__class__ # if class A is defined like class A(object):   ... 
>>> class aclass(object): ...   pass ... >>> a = aclass() >>> type(a) <class '__main__.aclass'> >>> a.__class__ <class '__main__.aclass'> >>> >>> type(a).__name__ 'aclass' >>> >>> a.__class__.__name__ 'aclass' >>>   >>> class bclass(): ...   pass ... >>> b = bclass() >>> >>> type(b) <type 'instance'> >>> b.__class__ <class __main__.bclass at 0xb765047c> >>> type(b).__name__ 'instance' >>> >>> b.__class__.__name__ 'bclass' >>> 

Questions similaires