Arthur Julião
Arthur Julião

Reputation: 869

self deleting instance

Is it possible to make a class call del() for some instances under some condition? Or turn self into None?

    class T:
        def __init__(self, arg1, arg2):
            condition=check_condition(arg1,arg2)
            if not condition:
               do_something(arg1)
            else:
               del(self) #or self=None or return None

I need to do something like this to be sure that will never exist a kind of instance.

Upvotes: 12

Views: 5938

Answers (5)

Niklas R
Niklas R

Reputation: 16900

The class constructor is intended to really construct an instance of its class and not fail half-silently by just not constructing an instance and returning None. Nobody would expect that behaviour.

Rather use a factory function.

class Test(object):
    @classmethod
    def create(cls):
        if ok(): return cls()
        else: return None

Upvotes: 1

NPE
NPE

Reputation: 500953

I need do something like this to be sure that will never exist a kind of instance.

If you simply want to prevent the creation of such an instance, raise an exception in __init__() whenever the condition is satisfied.

This is standard protocol for signalling constructor failures. For further discussion, see Python: is it bad form to raise exceptions within __init__?

Upvotes: 8

user1552512
user1552512

Reputation: 909

Yes, you can call del self. it works just fine, but you should know that all it's doing is deleting the reference to an instance, named "self" in the init method.

In python, objects exist as long as there is a reference to them somewhere.

If you want the object to never exist under certain conditions, then do not ever attempt to create an instance under those conditions, outside of init where you are creating the object.

Also, you could define a helpful function in this class to return whether those conditions are satisfied.

Upvotes: 2

Vic
Vic

Reputation: 22051

You can raise an exception as suggested in comments. You can implement __new__. Also you can make some factory class, like

class TFactory:
    def createT(self, arg1, arg2):
        condition=check_condition(arg1,arg2)
        if not condition:
           return do_something(arg1)
        else:
           return None     

Upvotes: 2

Hank Gay
Hank Gay

Reputation: 72039

Look into __new__. You should be able to detect the condition you care about and return None. As @lzkata mentions in the comments, raising an Exception is probably a better approach, though.

Upvotes: 3

Related Questions