how to use property?
Terry Reedy
tjreedy at udel.edu
Mon Sep 17 19:34:52 EDT 2012
More information about the Python-list mailing list
Mon Sep 17 19:34:52 EDT 2012
- Previous message (by thread): how to use property?
- Next message (by thread): how to use property?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 9/17/2012 6:12 PM, Chris Angelico wrote: > On Tue, Sep 18, 2012 at 7:55 AM, Fernando Jiménez <the.merck at gmail.com> wrote: >> Hi guys! >> >> I'm noob in python and I would know how to correctly use the property. I >> have read some things about it but I do not quite understand. >> >> But I think it's a bad habit to use _ to change the visibility of the >> attributes as in JAVA. >> >> How to correctly use the property? > > The single leading underscore is nothing to do with visibility; it's a > courteous request that external referents not touch something. In a > "consenting adults" model, that's usually sufficient. > > For the most part, in fact, you don't need @property at all. Just make > an object's members public and save yourself the trouble! Unlike the > recommendation in C++ and Java, Python doesn't ask you to hide things > and write code to make them available. Instead of starting with > getters and setters, just start with a flat property, and move to > getters/setters only when you find you need them. More examples: A class has a data attribute that really is a simple attribute, no property. You define a subclass that needs a calculation for the attribute. So you use property in the subclass. A class has an attribute that is a constant that must be computed. You do not want to compute is unless and until needed. def get_x(self): try: return self._x except AttributeError: self._x = calculate_x() return self._ For a read-only attribute, don't provide a setter. If you do not like "AttributeError: can't set attribute", provide one with a customized error. But I think most of the data attributes in stdlib classes are straight attributes. -- Terry Jan Reedy
- Previous message (by thread): how to use property?
- Next message (by thread): how to use property?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list