Can set any property of Python object

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

    This happens because when you say a.b = 3, it creates a variable in a that represents b. For example,

    class a: pass
    print a.b
    

    returns AttributeError: class a has no attribute b

    However this code,

    class a: pass
    a.b = 3
    print a.b
    

    returns 3 as it sets the value of b in a, to 3.

提交回复
热议问题