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)    
1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.