python - Terminology: A user-defined function object attribute? -
according python 2.7.12 documentation, user-defined methods:
user-defined method objects may created when getting attribute of class (perhaps via instance of class), if attribute user-defined function object, unbound user-defined method object, or class method object. when attribute user-defined method object, new method object created if class being retrieved same as, or derived class of, class stored in original method object; otherwise, original method object used is.
i know in python object, "user-defined method" must identical "user-defined method object". however, can't understand why there "user-defined function object attribute". say, in following code:
class foo(object): def meth(self): pass meth function defined inside class body, , method. why can have "user-defined function object attribute"? aren't attributes defined inside class body?
bouns question: provide examples illustrating how user-defined method object created getting attribute of class. isn't objects defined in class definition? (i know methods can assigned class instance, that's monkey patching.)
i'm asking because part of document really confusing me, programmer knows c, since python such magical language supports both functional programming , object-oriented programmer, haven't mastered yet. i've done lot of search, still can't figure out.
when do
class foo(object): def meth(self): pass you defining class foo method meth. however, when class definition executed, no method object created represent method. def statement creates ordinary function object.
if do
foo.meth or
foo().meth the attribute lookup finds function object, function object not used value of attribute. instead, using descriptor protocol, python calls __get__ method of function object construct method object, , method object used value of attribute lookup. foo.meth, method object unbound method object, behaves function defined, type checking. foo().meth, method object bound method object, knows self is.
this why foo().meth() doesn't complain missing self argument; pass 0 arguments method object, prepends self (empty) argument list , passes arguments on underlying function object. if foo().meth evaluated meth function directly, have pass self explicitly.
in python 3, foo.meth doesn't create method object; function's __get__ still gets called, returns function directly, since decided unbound method objects weren't useful. foo().meth still creates bound method object, though.
Comments
Post a Comment