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()
raise TypeError('must be an int or float')Cubecould raise an exception.