[Python] Where does the self argument come from?

Discussão em 'Python' iniciado por Stack, Junho 5, 2025.

  1. Stack

    Stack Membro Participativo

    I understand that self is implicitly passed as an argument to methods when they are called. I am learning about descriptors and understand how functions "become" methods, I understand (at least conceptually) that attributes are "bound" to objects, I have read multiple articles online and Raymond Hettinger's Descriptor how to.

    In the example below, though, I just don't understand where the reference to the instance of the Function f (i.e. the parameter self on __get__, for which an argument will be implicitly passed) comes from.

    I contrast this with the self parameter on f itself, which I understand will get passed as an argument to parameter obj on __get__ when __get__ is called.

    How does Python know, when __get__ is called, what underlying function needs to be passed to MethodType? I know this is the argument which is passed to self, but how/when does this happen? I thought I understood how self worked when I learned about __get__, and how the __get__ on the function Type can either return a Function or a MethodType.

    class Function:
    def __get__(self, obj, objtype=None):
    "Simulate func_descr_get() in Objects/funcobject.c"
    if obj is None:
    return self
    return MethodType(self, obj)

    class D:
    def f(self, x):
    return x

    Continue reading...

Compartilhe esta Página