2

I came to a pitfall trying to understand where does the __setattr__ method of user defined classes is set to objects in python 3.

as my understanding of attributes goes when I type:

x.y = z

in python code. what happens is that the __setattr__ function of x is called with the key 'y' and the value of z.

but then I wrote this code

#!/usr/local/bin/python3

obj = object()

class A(object):
    pass

a = A()

a.tmp = 123456
obj.tmp = 123456

this code crashes on the last line with the error

Traceback (most recent call last):
  File "main.py", line 11, in 
    obj.tmp = 123456
AttributeError: 'object' object has no attribute 'tmp'

I expected lines 10 and 11 to behave the same since I did not override the __setattr__ methods of object in A.

why did the behavior change between object and A?

jalanb
  • 1,097
  • 2
  • 11
  • 37
user3848844
  • 509
  • 6
  • 20
  • This doesn't really have anything to do with setattr or setattribute. – Daniel Roseman Jul 29 '14 at 08:32
  • @DanielRoseman Doesn't it? Or do `__dict__` assignments not pass through `__setattr__`? – jtbandes Jul 29 '14 at 08:33
  • They may do, but that wasn't my point: the `__setattr__` methods of `obj` and `a` here are exactly the same, the difference (as Alex points out in the duplicate) is that there is no `__dict__`. – Daniel Roseman Jul 29 '14 at 08:37

0 Answers0