python - Why is the __init__ method of Counter referred to as a descriptor? -


i reading __init__ method of counter class, , saw this:

if not args:     typeerror("descriptor '__init__' of 'counter' object "               "needs argument") 

i wasn't sure meant descriptor, checked python data model document , found this:

in general, descriptor object attribute “binding behavior”, 1 attribute access has been overridden methods in descriptor protocol: __get__(), __set__(), , __delete__(). if of methods defined object, said descriptor.

none of methods seem present in class definition, why __init_ referred descriptor?

in python, all functions descriptors (including __init__). how know self when they're used in class. example, can define function (foo) , when @ it's methods, i'll see foo has __get__ method makes adhere descriptor protocol:

>>> def foo(): ...   pass ...  >>> dir(foo) ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] >>> '__get__' in dir(foo) true 

so terminology used there @ least accurate. debated whether that's best term use...

i might have called "bound method" instead of descriptor, in python3.x, distinction between regular functions, bound methods , unbound methods becomes little more muddy (unbound methods are regular functions in python3.x)...


of course, use different type of descriptor initialize counter subclass ...

class mydescriptor(object):     def __get__(self, inst, cls):         # useless descriptor!         return counter.__init__.__get__(inst, cls)  class mycounter(counter):     __init__ = mydescriptor() 

and throw error, error message more accurate way, pretty crazy case wouldn't expect happen frequently.

to know raymond thinking when wrote code, suppose you'd have ask him (or go spelunking in hg commit history , hope mentioned in commit message).


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -