• Dynamically modifying "__setattr__"

    From Stefan Ram@21:1/5 to All on Thu Sep 28 09:44:01 2023
    I wanted to postpone the introduction of a custom __setattr__
    to a point later at runtime where I then wanted to use
    "self.__setattr__ = self.setattr" to set this attribute. But this
    did not have the effect desired to print "setattr called" as can
    be seen below.

    main.py

    class A:
    def __init__( self ):
    self.__setattr__ = self.setattr
    def setattr( self, key, value ):
    print( 'setattr called.' )

    a = A()
    a.x = 1

    transcript

    Any idea how to achieve something like this?

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Greg Ewing@21:1/5 to Stefan Ram on Sat Sep 30 16:54:21 2023
    On 28/09/23 10:44 pm, Stefan Ram wrote:
    class A:
    def __init__( self ):
    self.__setattr__ = self.setattr
    def setattr( self, key, value ):
    print( 'setattr called.' )

    Any idea how to achieve something like this?

    class A:

    def __init__(self):
    self.x = 17
    self.setattr = self.custom_setattr

    def __setattr__(self, key, value):
    self.setattr(key, value)

    def setattr(self, key, value):
    object.__setattr__(self, key, value)

    def custom_setattr(self, key, value):
    print('custom_setattr:', key, '=', value)

    a = A()
    a.x = 1
    print('a.x =', a.x)

    --
    Greg

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Stefan Ram@21:1/5 to Greg Ewing on Sat Sep 30 12:20:16 2023
    Greg Ewing <[email protected]> writes:
    def __setattr__(self, key, value):
    self.setattr(key, value)

    |All problems in computer science can be solved by
    |adding another level of indirection.

    (The fundamental theorem of software engineering [FTSE] is
    a term originated by Andrew Koenig to describe a remark by
    Butler Lampson attributed to the late David J. Wheeler.)

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)