Skip to content

Instantly share code, notes, and snippets.

@ParitoshSingh07
Created May 7, 2019 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ParitoshSingh07/f00c5928e49bad3859ee9075ad2f0a20 to your computer and use it in GitHub Desktop.
Save ParitoshSingh07/f00c5928e49bad3859ee9075ad2f0a20 to your computer and use it in GitHub Desktop.
class Bomb:
def __init__(self):
raise RuntimeError('BOOM')
bomb = Bomb.__new__(Bomb) # YOUR CODE HERE
assert type(bomb) is Bomb, "You didn't create a Bomb instance, did you?"
print('You win!')
@alkasm
Copy link

alkasm commented May 7, 2019

Python's object creation has two steps; create the object, then initialize it. Normally, you never call __new__, this happens automatically when you instantiate an object like Bomb(). __new__ returns the object itself, and then that gets passed into __init__ to be initialized. Since you called __new__ yourself, you're in charge of initializing it, but you didn't, so you subverted the RuntimeError.

That's why if you create your own __new__ method, you have to actually return the object, but __init__ doesn't, because it just uses the object created in __new__.

@ParitoshSingh07
Copy link
Author

ParitoshSingh07 commented May 7, 2019

Ooh! that's wicked. I just tried to work backwards, first seeing the assert, then i wrote a Dir on the Bomb class. New looked promising, and i ran it without any argument. It complained. Then i wrote a random string, it complained again. So i passed Bomb... Pretty wicked, tyvm for the explanation. Need a second to grok it though, objects dont come intuitively to me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment