Reputation: 21
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)
Upvotes: 0
Views: 168
Reputation: 101
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.
Upvotes: 1