Does python has "apply" alike approach like the other languages?

Viewed 59

In other languages, you can apply context to function, so you can have the context scope.

The similar thing I couldnt find relative reference for Python.

In below example, if I wana access context scope from outside, what can I do??

On below example, how can I access the class private method from outside function?

Relative example :

class a:
    def __b(S):
        print(11111)

    def c(S):
        d(S)  # how can I apply scope here??

---

def d(S):
    S.__b()


---

a().c()

Thank you very much.

1 Answers

You can bind an unbound function to an object with types.MethodType:

from types import MethodType

class a:
    def b(S):
        print(11111)

    def c(S):
        MethodType(d, S)()

def d(S):
    S.b()

a().c()

This outputs: 11111

It does not, however, let outside functions access "private" methods that are prefixed with double underscores due to name mangling at compilation time.

Related