Best way to set/get an object property

Hussein B hubaghdadi at gmail.com
Mon Aug 25 02:56:27 EDT 2008


On Aug 24, 7:12 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Sun, 24 Aug 2008 12:28:53 +0200, Peter Otten wrote:
> > Hussein B wrote:
>
> >> I noted that Python encourage the usage of: --
> >> obj.prop = data
> >> x = obj.prop
> >> --
> >> to set/get an object's property value. What if I want to run some logic
> >> upon setting/getting a property? What is Python preferred method to do
> >> so (using the new feature 'property')?
> >> I don't think __getattr__ and __setattr__ are practical (I have to code
> >> the property name into them).
>
> > Hussein, I don't think you'll learn much from asking these abstract
> > questions. At some point you have to get your hands dirty and write
> > actual code to get a feel for the language.
>
> > For example, it will then become obvious for you that property works
> > best for individual attributes while __getattr__ and friends are more
> > convenient if you want to treat multiple attributes the same way,
> > attributes whose names may not even be known until runtime (think
> > delegation).
>
> I think you are misunderstanding Hussein's question. I believe that he is
> using "property" to refer to what we would call an attribute. Naturally I
> could be wrong, but this is how I interpret his question.
>
> I think the actual answer to his question is that properties are the
> preferred way to "run some logic upon setting/getting" an attribute, that
> is, to implement getters and setters.
>
> Hussein, the Java habit of writing setters and getters for everything
> isn't considered good practice in Python, but if you need them, that's
> exactly what the property() function is for.
>
> --
> Steven

Thank you Steven :)
--
public class JClass {
  private int answer; // property
}
--
class PyClass(object):
  doc __init__(self):
    self.answer = None
--
AFAIUY (understand you), what it is called a property in Java, it is
called an attribute in Python?
Why Python encourages direct access to object's attributes?  aren't
setters/getters considered vital in OOP (encapsulation)?
Thank you all for your time and help.



More information about the Python-list mailing list