2

E.g.

def __setattr__(self, name, value):
    ...

works fine, however:

def __init__(self):
    self.__setattr__ = foo

doesn't seem to achieve anything in that foo is never called.

Thanks in advance.

Michael
  • 2,258
  • 1
  • 23
  • 31

1 Answers1

1

__setattr__ uses the class method, not the instance method. Examine the output of the following code:

Code:

def func(*args):
    print "--Func--"
    print args

class A():
    def __setattr__(*args):
        print "--SetAttr--"
        print args


a = A()

print "a.x = 10"
a.x = 10
print

A.__setattr__ = func

print "a.y = 20"
a.y = 20
print

Output:

a.x = 10
--SetAttr--
(<__main__.A instance at 0x2cb120>, 'x', 10)

a.y = 20
--Func--
(<__main__.A instance at 0x2cb120>, 'y', 20)

You could write your code such that the class method calls an instance method:

class C():
    def __init__(self, setattr):
        #Must access in this way since we overwrote __setattr__ already
        self.__dict__['setattr_func'] = setattr

    def __setattr__(self, name, value):
        self.setattr_func(name, value)
DrRobotNinja
  • 1,381
  • 12
  • 14