Descriptors vs Property

Thomas 'PointedEars' Lahn PointedEars at web.de
Sat Mar 12 12:13:50 EST 2016


Veek. M wrote:

> Veek. M wrote:
>> class TypedProperty(object):
>>     def __init__(self,name,type,default=None):
>>         self.name = "_" + name
>>         self.type = type
>>         self.default = default if default else type()
>> 
>>     def __get__(self,instance,cls):
>>         return getattr(instance,self.name,self.default)
>> […]
>> class Foo(object):
>>     name = TypedProperty("name",str)
>>     num  = TypedProperty("num",int,42)
>> […]
>> When you do f.name you are actually doing:
>> 
>> f.name.__get__(self, instance, cls)

Correct.

>> What the heck??
> As in, why is he passing instance, cls and who is populating those vars?

RTFM: 
<https://docs.python.org/3/reference/datamodel.html?highlight=__get__#implementing-descriptors>

> When you do f.name you just have self to pass into
> name.__whatever__(self)

No.

> I haven't read the descriptor protocol as yet.

You should.  You should also trim your quotations to the relevant minimum, 
and post using your real name.

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.



More information about the Python-list mailing list