You could override __setattr__ to only allow attribute names from a defined list.
class A(object):
def __setattr__(self, name, value):
allowed = ('x',)
if name in allowed:
self.__dict__[name] = value
else:
raise AttributeError('No attribute: %s' % name)
In operation:
>>> a = A()
>>> a.x = 5
>>> a.other = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "myc.py", line 7, in __setattr__
raise AttributeError('No attribute: %s' % name)
AttributeError: No attribute: other
However, as msw has commented, attempts to make Python behave more like Java or C++ are usually a bad idea and will lead to losing lots of the benefits that Python provides. If you are concerned about making typos that might be missed then you are much better spending time writing unit tests for your code than trying to lock down the usage of your classes.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…