-1

How to override a magic method for the current script?

def __setattr__(name, value):
    __dict__[name] = value
    print("asd")
    if name == 'b':
        print(__dict__[name])


if __name__ == '__main__':
    a = 3
    b = 4
    b = 5

In above, for example, I expect assignments to b to call __setattr__ but they don't. What am I missing?

Nae
  • 14,209
  • 7
  • 52
  • 79
  • 1
    Could someone direct me how exactly the question is unclear? So that I can clarify it better. – Nae Feb 10 '18 at 15:17

2 Answers2

2

__setattr__ only applies to assignments of the form a.b = c, which translates to type(a).__setattr__(b, c). Simple name assignments are a fundamental operation of the language itself, not implemented by any magic method.

You are just defining a module level function named __setattr__, not a magic method of any particular class.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Thanks for your input, I don't think I fully understand it but that at the very least leads me in a direction for more research. – Nae Feb 10 '18 at 15:13
  • Is there any workaround for catching name assignments of the current script to call a method when it happens on a particular name? – Nae Feb 10 '18 at 15:15
  • 1
    No. As I said, name assignments are a *fundamental* operation; it's not implemented in terms of a lower-level operation that you can override. Assignment just *is*. – chepner Feb 10 '18 at 15:20
0

EDIT: I realised I made a mistake. Your question if how to overwrite a method without using a class. This is not possible in python, because methods can only be invoked on objects, which are derived from a class.

For starters, you may want to consider defining a class. Methods are called upon objects (magic methods, normal methods, all the same), and objects in turn are derived from their classes. Note that in python everything is an object. There are a couple of classes that come within the standard python library like String, Integer, Boolean, and so on. Your code would have to look more like the following:

def class Some_Class:
    name = ""
    __init__(self,name):
        self.name = name

    __setattr__(self,name,value):
        if name == "b":
            self.doSomething()

    def doSomething():
        pass

def main():

    example_class = Some_Class('Chars')
    setattr(example_class, 'b','some_value') #Will trigger doSomething()

main()
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Brakke Baviaan
  • 460
  • 3
  • 10