-
-
Save ParitoshSingh07/f00c5928e49bad3859ee9075ad2f0a20 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!') |
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
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 likeBomb()
.__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 theRuntimeError
.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__
.