0

I'm trying to create a sample object to test the __new__ and __init__ method.

Here is my sample code. When I run this - I see "Its been created" msg and dont see the "Initialized" & "Deleted" msg.

class Test( object ):
    def __new__(self):
        print 'Its been Created'

    def __init__(self):
        print 'Its been Initialzed'

    def __del__(self):
        print 'Its been Deleted'


T = Test()        
1
  • er, why are you defining __del__, you probably don't want to do that... Commented Mar 5, 2014 at 16:18

1 Answer 1

3

__new__ needs to return an instance of the class (see docs). What you're effectively doing here is returning the instance on NoneType (since functions with no explicit return value return None (and 'the' in this case because None is a special-case singleton in Python)), then having __init__ of that object called. The simplest way to fix this would be something like:

class Test(object):

    def __new__(cls):
        print 'Creating'
        return super(Test, cls).__new__(cls)

    def __init__(self):
        print 'Intializing'

    def __del__(self):
        print 'Deleting'

This will cause Test.__new__() to return the result of Test's superclass' (object in this case) __new__ method as the newly created instance.

It may help you to understand what's going on if you try the following:

class A(object):

    def __new__(cls):
        print 'A.__new__'
        return super(A, cls).__new__(cls)

    def __init__(self):
        print 'A.__init__'

    def __del__(self):
        print 'A.__del__'

class FakeA(object):

    def __new__(cls):
        print 'FakeA.__new__'
        return A.__new__()

    def __init__(self):
        print 'FakeA.__init__'

    def __del__(self):
        print 'FakeA.__del__'

a = A()
fa = FakeA()
del a
del fa

However, it is important to note that __del__ is not guaranteed to be called on every instance every time.

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.