0

I ran into a small trouble when I was trying to write a small piece of code to avoid creating instance of a class in Python 2.7. The problem is that when I didn't extend object' and tried to raise an exception in the '__new__' method the '__init__' method just got called (which means the object was created fine) and the flow continued. But when I did extend 'object' things seemed to work as expected which was raising the exception.

I would like to know what might be the reason for this.

I couldn't find an answer in Stackoverflow, if you guys feel this is a duplicate and it would be better if you could point me to the right direction.

from classcreator import AbstractionException

class test():
    def __new__(self):
        try:
            raise AbstractionException("Can't instantiate class")
        except AbstractionException:
            print ('OOPS !!! ')

    def __init__(self):
        self.name='Hello'

    def __str__(self):
        return self.name

x=test()
print(x)    
DSM
  • 342,061
  • 65
  • 592
  • 494
VMS ALDO
  • 21
  • 5
  • 5
    I imagine this is because of old-style vs new-style classes: http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python – Ismail Badawi Jun 05 '14 at 19:08

1 Answers1

1

The reason of such behaviour is using old-style classes. Those classes don't have __new__() static method. Here is the brilliance article by Guido van Rossum, describing the difference between the new-style and old-style classes.