0
class Person:
    pass

smith = Person()
smith.gender = "Female"

print(smith.gender)  # prints 'Female' in console

This is the question I have, cuz Person class should not contain the attribute 'gender'.

I want to throw an error like "class 'Person' does not have attribute 'gender'" when people try to add this gender attribute to the object. How can I do that?

init 1
  • 39
  • 6
  • 1
    [Prevent creating new attributes outside __init__](https://stackoverflow.com/questions/3603502/prevent-creating-new-attributes-outside-init) check this answer. – fayez Dec 11 '20 at 16:26
  • Adding static analyzers (e.g. `mypy`) to your test suite and rejecting code that doesn't pass those tests is IMO an easier solution than trying to enforce it at runtime. – Samwise Dec 11 '20 at 17:04

0 Answers0