Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

self deleting instance

Tags:

python

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.

like image 727
Arthur Julião Avatar asked Nov 06 '12 21:11

Arthur Julião


People also ask

How do I disable GCP deletion protection?

To disable deletion protection, set deletionProtection to false . // and waits for it to complete.

What is the Gcloud command to list compute instances?

gcloud compute instances list lists summary information for the virtual machine instances in a project. The “--uri” option can be used to display the URIs of the instances' in the project. Users who want to see more data should use gcloud compute instances describe . By default, instances from all zones are listed.


2 Answers

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__?

like image 180
NPE Avatar answered Sep 28 '22 10:09

NPE


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.

like image 30
Hank Gay Avatar answered Sep 28 '22 11:09

Hank Gay