Property Descriptor - Public Getter, Private Setter

G

gamehack

Hi all,

I was looking around the net to figure out how I can use the
property() descriptor to make a property readable by everyone and only
settable by the class or any derived classes. Thanks.

Regards,
gh
 
D

Diez B. Roggisch

gamehack said:
Hi all,

I was looking around the net to figure out how I can use the
property() descriptor to make a property readable by everyone and only
settable by the class or any derived classes. Thanks.

Forget it. You can try and come up with an implementation that will check
the stack-frames and try and see if the callers belong to the current
class, or some subclass.

But then if somebody wants to accomplish the setting by all means, he/she
just adds a new setter method to your class, and that's it.

What's your usecase? If you give us that, there might be better suggestions.

Diez
 
J

James Stroud

gamehack said:
Hi all,

I was looking around the net to figure out how I can use the
property() descriptor to make a property readable by everyone and only
settable by the class or any derived classes. Thanks.

Regards,
gh

Congratulations, you have discovered a principal use of properties--to
restrict access! But how? By the honor system, of course, and some
clever naming techniques and documentation. Below we see all of the
essential components.

1. clever naming -- our attribute is prepended with an underscore,
signifying its special status as an internal
name and will not be exposed to the API.
2. documentation -- we let our users know about the value property
3. properties -- we make a property named value that is exposed
to the API, but we don't expose _value as it
is not available beyond the class and subclasses
implicitly, by virtue of clever naming (see 1)

class C(object):
"""
Instances of this class are endowed with a 'value' property.
This property is read-only for users of the API. Have a Nice Day.
"""
def __init__(self):
self._value = None
def get_value(self):
return self._value
value = property(get_value)


James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top