Best way to set/get an object property

H

Hussein B

Hey,
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).
Thanks.
 
P

Peter Otten

Hussein said:
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).

Peter
 
H

Hussein B

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).

Peter

Thanks Peter,
You are right, I have to try to touch the Python but the problem is I
don't have much time to do so.
I have a Java developer for more than 4 years and I find it is not so
easy to digest Python concepts, this is why I'm asking a lot of
obvious and clear easy to you (long time Pythonists).
Thank you for your time.
 
C

castironpi

Hey,
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).
Thanks.

The answer Hussein is you have both options in Python. If neither one
is clearly better-suited to your new application, pick one and go.
 
S

Steven D'Aprano

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.
 
H

Hussein B

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.

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.
 
A

alex23

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?

The simplest answer is "Because Python is not Java" :)

Speaking of which, have you read the blog post of the same name? It
might be useful given your Java background: http://dirtsimple.org/2004/12/python-is-not-java.html
 aren't
setters/getters considered vital in OOP (encapsulation)?

Not at all. They're definitely part of the mechanism that Java
provides for encapsulation, sure. However, because Python provides a
consistent interface for accessing attributes and properties, you
don't need to define a property unless your code requires it. If all
your getters & setters are doing is reading & writing to an attribute,
then why not just r&w directly to the attribute? If you later need to
add more complexity to that process, you can easily create a property
without having to change how any other piece of code refers to that
property, given it shares the same interface with attributes.
 
S

Steven D'Aprano

On Aug 24, 7:12 pm, Steven D'Aprano <st...@REMOVE-THIS-
cybersource.com.au> wrote:

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.


Hussein, first let me ask you to please stop using "--" as a separator
around code. Many News clients, including mine, expect -- on a line by
itself to mean "everything from here on is the writer's signature", and
consequently that makes it harder to reply correctly to your posts. I had
to manually copy and paste your text in order to quote it. Perhaps you
could use === or +++ or *** as a separator?


Now, back to your actual question...

I'm not a Java coder, so the following should be read as my opinion.
Python attributes are equivalent to Java _public_ properties, not
private. If you can write:

public class JClass {
public int answer;
}

then that would be more or less equivalent to Python's

class PyClass(object):
def __init__(self):
self.answer = None


Yes, Python does encourage direct access to an object's attributes. The
Python philosophy is "we're all adults here". If coders wish to shoot
themselves in the foot by accessing clearly marked private attributes,
then the language can't stop them and shouldn't try. It's easy to bypass
such private/public protection in C++, and harder, but still possible, in
Java.

The Python development team is certainly aware that such a tactic
introduces some costs, by reducing encapsulation, but it also has many
benefits (e.g. less boilerplate getter/setter methods, faster development
time). It is their belief that such costs are worth paying in order to
get the benefits. That's the philosophy of the language. Python is not
trying to be Java, and Java should not try to be Python.

Python does not enforce private attributes. By convention attributes
starting with a single underscore are considered "private -- don't touch
unless you know what you're doing". Attributes starting with a double
underscore are "really private", and Python mangles the name to (almost)
enforce it.

Example:

def Parrot(object):
colour = 'red' # public, free to use
_windspan = 15 # semi-private, use it at your own risk
__species = 'Norwegian Blue' # mangled to _Parrot__species


But it's quite rare to see double-underscore "really private" attributes
in Python code. It is considered to go against the spirit of the language.

I'm told that in Java it is quite difficult to change a class from using
public attributes to getters/setters, and therefore many Java developers
prefer to use getters/setters right from the beginning. But in Python it
is very easy to change from a bare attribute to a computed property
without messing up calling code. So there's no advantage to writing
something like this:

class Foo(object):
def __init__(self):
self.__x = None # private attribute
def setx(self, x): # setter
self.__x = x
def getx(self): # getter
return self.__x
x = property(getx, setx)


That is considered a waste of time in Python circles and is strongly
discouraged.

You should read "Python Is Not Java" and "Java Is Not Python Either":

http://dirtsimple.org/2004/12/python-is-not-java.html

http://dirtsimple.org/2004/12/java-is-not-python-either.html
 
H

Hussein B

Hussein, first let me ask you to please stop using "--" as a separator
around code. Many News clients, including mine, expect -- on a line by
itself to mean "everything from here on is the writer's signature", and
consequently that makes it harder to reply correctly to your posts. I had
to manually copy and paste your text in order to quote it. Perhaps you
could use === or +++ or *** as a separator?

Now, back to your actual question...

I'm not a Java coder, so the following should be read as my opinion.
Python attributes are equivalent to Java _public_ properties, not
private. If you can write:

public class JClass {
public int answer;

}

then that would be more or less equivalent to Python's

class PyClass(object):
def __init__(self):
self.answer = None

Yes, Python does encourage direct access to an object's attributes. The
Python philosophy is "we're all adults here". If coders wish to shoot
themselves in the foot by accessing clearly marked private attributes,
then the language can't stop them and shouldn't try. It's easy to bypass
such private/public protection in C++, and harder, but still possible, in
Java.

The Python development team is certainly aware that such a tactic
introduces some costs, by reducing encapsulation, but it also has many
benefits (e.g. less boilerplate getter/setter methods, faster development
time). It is their belief that such costs are worth paying in order to
get the benefits. That's the philosophy of the language. Python is not
trying to be Java, and Java should not try to be Python.

Python does not enforce private attributes. By convention attributes
starting with a single underscore are considered "private -- don't touch
unless you know what you're doing". Attributes starting with a double
underscore are "really private", and Python mangles the name to (almost)
enforce it.

Example:

def Parrot(object):
colour = 'red' # public, free to use
_windspan = 15 # semi-private, use it at your own risk
__species = 'Norwegian Blue' # mangled to _Parrot__species

But it's quite rare to see double-underscore "really private" attributes
in Python code. It is considered to go against the spirit of the language.

I'm told that in Java it is quite difficult to change a class from using
public attributes to getters/setters, and therefore many Java developers
prefer to use getters/setters right from the beginning. But in Python it
is very easy to change from a bare attribute to a computed property
without messing up calling code. So there's no advantage to writing
something like this:

class Foo(object):
def __init__(self):
self.__x = None # private attribute
def setx(self, x): # setter
self.__x = x
def getx(self): # getter
return self.__x
x = property(getx, setx)

That is considered a waste of time in Python circles and is strongly
discouraged.

You should read "Python Is Not Java" and "Java Is Not Python Either":

http://dirtsimple.org/2004/12/python-is-not-java.html

http://dirtsimple.org/2004/12/java-is-not-python-either.html

Thank you all guys and big thank you Steven, I owe you a beer.
Sorry, I wasn't aware of the two dashes problem as I use Google Group/
Reader.
comp.lang.python really rocks & much more friendly and useful than
comp.lang.ruby
 
B

Bruno Desthuilliers

Steven D'Aprano a écrit :
(snip)
But it's quite rare to see double-underscore "really private" attributes
in Python code. It is considered to go against the spirit of the language.

Not necessarily "against the spirit" - it's mostly than __name_mangling
is only really useful when you want to protect a really vital
implementation attribute from being *accidentaly* overridden, and mostly
annoying anywhere else.
I'm told that in Java it is quite difficult to change a class from using
public attributes to getters/setters,

That's an understatement. Java has *no* support for computed attributes,
so you just can *not* turn a public attribute into a computed one.
and therefore many Java developers
prefer to use getters/setters right from the beginning.

Truth is that they have no other choice if they want to be able to
decouple implementation from interface.
 

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,774
Messages
2,569,596
Members
45,130
Latest member
MitchellTe
Top