Skip to content
Advertisement

How do I create a class where instantiation only happens if certain conditions are met?

Let’s say I have this class:

JavaScript

If I want to instantiate Person I can do:

JavaScript

But what if I only want to instantiate Person if name has type str?
I tried this:

JavaScript

But then when I do:

JavaScript

I get this:

enter image description here

So all that’s happening is:

  • If name is str, the instance has a .name method
  • If name is not str, the instance has no .name method

But what I actually want, is to stop instantiation all together if name is not an str.
In other words, I want it to be impossible to create an object from the Person class with a non str name.

How can I do that?

Advertisement

Answer

You could use a factory that checks the parameters, and returns a Person object if everything is fine, or raises an error:

maybe something line this:

JavaScript

Whereas:

JavaScript

throws an exception:

JavaScript
Advertisement