I am using a Python API that expects me to pass a function. However, for various reasons, I want to give it a method, because I want to behave differently on the basis of this function. If I pass it through a method, then the API will not call it right with 'self' logic, so I am thinking about how to change a method in a function, which knows what it is that is itself. There are some ways, including using lambda and closing, which I can do about this. I have included some examples below, but I am thinking that there is a standard mechanism for achieving the same effect.
class A (object): def hello (self, greetings): print ('% s, my name% s'% (Hello, str (self)) def bind_hello1 (self) Return: Lambda X: Self. Hello (x) def bind_hello2 (self): DEF hello2 (* args): self Hilo (* Args) returns Hello 2 & gt; & Gt; & Gt; A1, a2 = A (), A ()> gt; & Gt; & Gt; A1.hello ('hello'); A2.hello ('Greetings') Hello, my name is & lt; __ Main __. One object at 0x71570 & gt; Hello my name & lt; __ is the main __. An object on 0x71590 & gt; & Gt; & Gt; & Gt; F1, f2 = a1.bind_hello1 (), a2.bind_hello1 () >> gt; & Gt; F1 ('greetings'); F2 ('salute') Hello, my name is & lt; __ Main __. One object at 0x71570 & gt; Hello my name is & lt; __ Main __. An object on 0x71590 & gt; & Gt; & Gt; & Gt; F1, f2 = a1.bind_hello2 (), a2.bind_hello2 ()> & gt; & Gt; F1 ('aloha'); F2 ('Aloha') Aloha, my name & lt; __ is the main __. One object at 0x71570 & gt; Aloha, my name & lt; __ is the main __. An object on 0x71590 & gt;
Will an example in the law be bound to work? If so, then you do not have to do anything special.
in [2]: Category C: Object: ...: Def method (self, A, B, C): ...: Print A, B, C ... ... ... in: [3]: DEF API_Function (A_Funk): ...: A_Funk ("One Fish", "Two Fish", "Blue Fish") ... ... in: [4 ]: C = C () in [5]: api_function (c.method) A fish two fish blue fish
Comments
Post a Comment