Can set any property of Python object

后端 未结 5 1223
长发绾君心
长发绾君心 2020-12-30 07:21

For example, this code is Python:

a = object()
a.b = 3

throws AttributeError: \'object\' object has no attribute \'b\'

5条回答
  •  滥情空心
    2020-12-30 08:24

    Python generally allows you to set any attribute on any object. This is a special case where the object class acts differently. There are also some modules implemented in C that act similarly.

    If you want your object to behave like this, you can define a __setattr__(self, name, value) method that explicitly does a raise AttributeError() if you try to set a member that's not on the "approved list" (see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/389916)

提交回复
热议问题