首页 > 解决方案 > 如何防止其他人向 Python 中的对象/类添加新属性?

问题描述

class Person:
    pass

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

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

这是我的问题,因为 Person 类不应该包含属性“gender”。

当人们尝试将此性别属性添加到对象时,我想抛出类似“类'Person'没有属性'gender'”的错误。我怎样才能做到这一点?

标签: pythonpython-3.xclassattributes

解决方案


推荐阅读