Skip to content Skip to sidebar Skip to footer

How To Override A Magic Method For The Current Script Without A Class?

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])

Solution 1:

__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.

Solution 2:

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:

defclass Some_Class:
    name = ""
    __init__(self,name):
        self.name = name

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

    defdoSomething():
        passdefmain():

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

main()

Post a Comment for "How To Override A Magic Method For The Current Script Without A Class?"