1

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()
9
  • 1
    Why not just raise an error? raise TypeError('must be an int or float') Commented Sep 23, 2020 at 20:26
  • Metaclasses will help doing this, but if you want language-agnostic approach then you can use a function to create the instance and check the arguments before creating the instance. Commented Sep 23, 2020 at 20:27
  • @Tgsmith61591 Thanks for the fast answer, good idea but an error kills the code right? so when i learn afterwards the inputs and the person enters a string the program stops and he has to start all over again, than just entering an int or float in the next try. Commented Sep 23, 2020 at 20:29
  • 2
    @DKay36 The user can catch the error if they want. You just need to document that Cube could raise an exception. Commented Sep 23, 2020 at 20:32
  • 1
    You can search up try-except blocks to learn how to capture exceptions and either ignore or handle them. Commented Sep 23, 2020 at 20:42

1 Answer 1

2

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.

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.