I don\'t know for why using __setattr__ instead simple referencing like x.a=1.
I understand this example:
class Rectangle:
The first use of __setattr__ is to be overwritten in a class definition.
class Foo ( object ) :
def __init__ ( self ) :
self.x = 'looser'
def __setattr__ ( self, name, value ) :
if name == 'x' :
print( 'Hello, {} !'.format( value ) )
self.x = value
Problem, Foo() will print an infinite sequence of :
'Hello, looser !'
There comes the second use which is that, when you're doing that, you can call setattr from the parent class (object by default) to avoid infite recursion :
class Foo ( object ) :
def __setattr__ ( self, name, value ) :
self.bar( name, value )
object.__setattr__( self, name, value )
def bar ( self, name, value ) :
print( 'Setting {} to {}.'.format( name, value ) )
And therefore :
f = Foo()
>> 'Hello, winner !'
f.x
>> 'winner'