0
class Person:
    def __new__(cls, *args):
        if not all(isinstance(x, str) for x in args):
            raise TypeError(
                f'invalid argument {1??} in {invalid_person??}'
                f'{last_name??} must be string'
            )
        return super().__new__(cls)

    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

    def __str__(self):
        return f'{self.first_name} -  {self.last_name}'


if __name__ == '__main__':
    person = Person('john', 'dow')
    print(person)
    # error here
    invalid_person = Person('john', 1)

Hello. this is example. how to output an error in which place the error occurred, the name of the argument, the name of the attributes in the class and the name of the instance of the class? Or maybe there is a better way to implement validation when instantiating a class?

kapithan
  • 23
  • 6
  • Does this answer your question? [Manually raising (throwing) an exception in Python](https://stackoverflow.com/questions/2052390/manually-raising-throwing-an-exception-in-python) – qorka Apr 06 '22 at 21:02
  • did not found how to pass my variables to f string – kapithan Apr 06 '22 at 21:16
  • Why not type check in `__init__`? Something like `if not type(last_name) == str: raise()` – qorka Apr 08 '22 at 15:40

0 Answers0