0

I created a class, that accepts an argument, and when the type of this argument is not string, it raises an exception. Well, it raises the exception when I want to create an object of this class and the argument is not string, but it creates the object anyway. Is there any way to prevent object from creation?

class Movie():
    def __init__(self, name):
        if type(name) != str:
            raise Exception("name should be string")
        else:
            self.name = name

movie = Movie(1)

Here I get the exception but if I print(movie), I get the location of the object in the memory. I want to get an error, that this name is not defined. Thanks in Advance.

12
  • 2
    probably you would want to override the new method since that controls the creation of an object - see this post Commented Aug 6, 2019 at 6:27
  • 2
    Maybe with "del self" before raise Commented Aug 6, 2019 at 6:28
  • 3
    Cannot reproduce? Commented Aug 6, 2019 at 6:30
  • If I run your code then "movie" is not defined Commented Aug 6, 2019 at 6:31
  • 2
    Also it's better to use isinstance(foo, str) instead of type(foo) == str Commented Aug 6, 2019 at 6:37

1 Answer 1

2

Solution, del self object before raise

class Movie():
    def __init__(self, name):
        if type(name) != str:
            del self
            raise Exception("name should be string")
        else:
            self.name = name
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.