>>> class person(object):def init(self,name):self.name=namedef info(self)print "My name is {0}, I am a {1}".format(self.name,self.__class__.__name__)>>> bob = person(name='Robert')>>> bob.info()My name is Robert, I am a person
type(instance).__name__ != instance.__class__.__name__# if class A is defined likeclass A():...
type(instance) == instance.__class__# if class A is defined likeclass 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'>>>
class Spam:def meth(self):passclass Bar:pass
>>> s = Spam()>>> type(s).__name__'Spam'>>> type(s).__qualname__'Spam'>>> type(s).Bar.__name__ # type not needed here'Bar'>>> type(s).Bar.__qualname__ # type not needed here'Spam.Bar'>>> type(s).meth.__name__'meth'>>> type(s).meth.__qualname__'Spam.meth'