Search code examples
pythonclassdel

Python: Deleting a class instance


I'm new to Python and try to code some extras in my lerning lessons so now i need to code a class that crates an cube and than two methods. The methods are not the problem, but i want to generate a fail-save when creating my cube.

When you create the cube with any other types than int or float it should return that thats invalid and delete the created instance. I googled, tried and can't figure out how to get it done.

I also would like to generate the instance name inside the fail-save text. So it says "[...]instance "a" will be deleted[...]" when i create:

a = Cube("not an int or float")

and: "[...]instance "b" will be deleted[...]" when i try to create:

b = Cube("not an int or float")

Code:

class Cube():
    def __init__(self, length):
        if type(length) == int or type(length) == float:
            self.length = length
        else:
            print("The type of length has to be int or float.\nThe instance (a) will be deleted!!")
            del self
        
    def surface(self):
        print("surface")
    
    def volume(self):
        print("volume")
        

# creating an instance of the cube-class 
a = Cube("not an int or float")

# and test the methods
a.surface()
a.volume()

Solution

  • Simply raise an exception if there is a problem with initialization. The exception will prevent the assignment from taking place, which means the object will be subject to immediate garbage collection, so you don't need to use del (which has no real effect anyway; del just decrements the reference count of the object by deleting the name, but the name self would go out of scope anyway, with the same effect).

    Use isinstance to check the type of the parameter.

    class Cube:
        def __init__(self, length):
            if not isinstance(length, (int, float)):
                raise TypeError("Length must be an int or a float")
    
            self.length = length
    
        ...
    

    Ideally, though, you leave the burden to the caller to provide the correct type. You can use type hints to make it easier for the user to catch such errors:

    from typing import Union
    
    
    class Cube:
        def __init__(self, length: Union[int, float]):
            self.length = length
    
        ...
    

    A tool like mypy can be used to check statically that no attempt to pass a different type of argument.