Can set any property of Python object

后端 未结 5 1194
长发绾君心
长发绾君心 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:25

    The object type is a built-in class written in C and doesn't let you add attributes to it. It has been expressly coded to prevent it.

    The easiest way to get the same behavior in your own classes is to use the __slots__ attribute to define a list of the exact attributes you want to support. Python will reserve space for just those attributes and not allow any others.

    class c(object):
        __slots__ = "foo", "bar", "baz"
    
    a = c()
    
    a.foo = 3  # works
    a.b   = 3  # AttributeError
    

    Of course, there are some caveats with this approach: you can't pickle such objects, and code that expects every object to have a __dict__ attribute will break. A "more Pythonic" way would be to use a custom __setattr__() as shown by another poster. Of course there are plenty of ways around that, and no way around setting __slots__ (aside from subclassing and adding your attributes to the subclass).

    In general, this is not something you should actually want to do in Python. If the user of your class wants to store some extra attributes on instances of the class, there's no reason not to let them, and in fact a lot of reasons why you might want to.

提交回复
热议问题