Python: self .__ class__ vs. type (self)

I am wondering if there is a difference between

class Test(object): def __init__(self): print self.__class__.__name__ 

and

 class Test(object): def __init__(self): print type(self).__name__ 

?

Is there any reason to prefer one or the other?

(In my case, I want to use it to determine the name of the log, but I think it doesn't matter)

+49
python
Apr 30 2018-12-12T00:
source share
2 answers
 >>> class Test(object): pass >>> t = Test() >>> type(t) is t.__class__ True >>> type(t) __main__.Test 

So these two are the same. I would use self.__class__ , as it is more obvious what it is.

However, type(t) will not work for old-style classes, since the instance type of the old-style class is instance , and the instance type of the new-style class is its class:

 >>> class Test(): pass >>> t = Test() >>> type(t) is t.__class__ False >>> type(t) instance 
+31
Apr 30 2018-12-12T00:
source share
— -

As far as I know, the latter is the best way to do the former.

This is actually not so unusual in Python, consider repr(x) , which simply calls x.__repr__() or len(x) , which simply calls x.__len__() . Python prefers to use built-in functions for common functions that you are likely to use in different classes, and usually implements them by calling the __x__() methods.

+4
Apr 30 2018-12-12T00:
source share



All Articles