Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: self.__class__ vs. type(self) [duplicate]

Tags:

python

I'm 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 a reason to prefer one or the other?

(In my use case I want to use it to determine the logger name, but I guess this doesn't matter)

like image 866
Martin Schulze Avatar asked Apr 30 '12 15:04

Martin Schulze


People also ask

What is __ self __ in Python?

self represents the instance of the class. By using the “self” we can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes.

What does self __ class __ do?

self. __class__ is a reference to the type of the current instance. Throwing an exception here is like using an assert statement elsewhere in your code, it protects you from making silly mistakes. type() should be preferred over self.

Can I pass self to another class Python?

There is absolutely no problem with that. self is just a reference to the instance, it is not private nor is it dangerous to pass it to other functions.

What is Self in Self Python?

The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.


2 Answers

>>> class Test(object): pass >>> t = Test() >>> type(t) is t.__class__ True >>> type(t) __main__.Test 

So those two are the same. I would use self.__class__ since it's more obvious what it is.

However, type(t) won't work for old-style classes since the type of an instance of an old-style class is instance while the type of a new-style class instance is its class:

>>> class Test(): pass >>> t = Test() >>> type(t) is t.__class__ False >>> type(t) instance 
like image 178
ThiefMaster Avatar answered Sep 22 '22 23:09

ThiefMaster


As far as I am aware, the latter is just a nicer way of doing the former.

It's actually not that unusual in Python, consider repr(x), which just calls x.__repr__() or len(x), which just calls x.__len__(). Python prefers to use built-ins for common functions that you are likely to use over a range of classes, and generally implements these by calling __x__() methods.

like image 34
Gareth Latty Avatar answered Sep 24 '22 23:09

Gareth Latty