What is the purpose of checking self.__class__?

Viewed 54913

What is the purpose of checking self.__class__ ? I've found some code that creates an abstract interface class and then checks whether its self.__class__ is itself, e.g.

class abstract1 (object):
  def __init__(self):
    if self.__class__ == abstract1: 
      raise NotImplementedError("Interfaces can't be instantiated")

What is the purpose of that? Is it to check whether the class is a type of itself?

The code is from NLTK's http://nltk.googlecode.com/svn/trunk/doc/api/nltk.probability-pysrc.html#ProbDistI

5 Answers

In Python 3 either using type() to check for the type or __class__ will return the same result.

class C:pass
ci=C()
print(type(ci)) #<class '__main__.C'>
print(ci.__class__) #<class '__main__.C'>

I recently checked the implementation for the @dataclass decorator (Raymond Hettinger is directly involved into that project), and they are using __class__ to refer to the type.

So it is not wrong to use __class__ :)

Related