[Tutor] classproperty: readonly and inheritance - not more needed

Thomas Güttler guettliml at thomas-guettler.de
Fri Apr 21 06:51:28 EDT 2017


Am 20.04.2017 um 14:26 schrieb Steven D'Aprano:
> On Thu, Apr 20, 2017 at 10:39:57AM +0200, Thomas Güttler wrote:
>
>>> - its hard to get classproperty to work right.
>>
>> What is "righ"?
>>
>> In my case a read-only classproperty is enough. Inheritance should be
>> supported.
>>
>> I don't have a usecase for a setter.
>
> The standard library is not just for you :-)
>
> If Peter's solution is "good enough" for you, then great, go ahead and
> use it. But beware: of the two implementations I know, you cannot have
> both:
>
> - access from instances;
> - read-only property;
>
> You can have access from instances, but then the classproperty is not
> read-only. Or you can have read-only access, but only from the class
> object.

I can't follow what you. What do you mean with "... is not read-only".

This snippet works fine:

{{{

class classproperty(object):
     def __init__(self, f):
         self.f = f
     def __get__(self, obj, owner):
         return self.f(owner)

class Foo(object):
     @classproperty
     def my_prop(cls):
         return 42

print Foo.my_prop

print Foo().my_prop
}}}

Regards,
   Thomas

-- 
Thomas Guettler http://www.thomas-guettler.de/


More information about the Tutor mailing list