niXforums Forum Index
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   PreferencesPreferences   Log in to check your private messagesLog in to check your private messages   Log inLog in 
·  nixdoc.net ·  man pages ·  Linux HOWTOs ·  FreeBSD Tips ·  Forums
navigation Forum index » Programming » python
Accessors in Python (getters and setters)
Post new topic   Reply to topic Page 6 of 8 [116 Posts] View previous topic :: View next topic
Goto page:  Previous  1, 2, 3, 4, 5, 6, 7, 8 Next
Author Message
Ed Jensen
*nix forums beginner


Joined: 06 May 2005
Posts: 34

PostPosted: Wed Jul 19, 2006 4:53 pm    Post subject: Re: Accessors in Python (getters and setters) Reply with quote

Diez B. Roggisch <deets@nospam.web.de> wrote:
Quote:
Ah, you mean like in JAVA

Java is not an acronym. That is: it's "Java", not "JAVA".

Quote:
where the compiler prevents you from accessing
private variables, but the runtime allows access to these very variables
via reflection?

Java does not allow access to private members via reflection.
Back to top
bruno modulix
*nix forums Guru


Joined: 21 Feb 2005
Posts: 819

PostPosted: Wed Jul 19, 2006 4:54 pm    Post subject: Re: Accessors in Python (getters and setters) Reply with quote

mystilleef wrote:
Quote:
Bruno Desthuilliers wrote:

mystilleef wrote:
(snip)

Of course using setters for the sake of just using them is pointless.

Indeed.



The reason to use them is if pre-conditions or post-conditions need to
be met. Or to control access to an objects states.

Then why advocate *systematic* use of them ?

(snip)

I never advocated anything.

You advocated
"""
1). Make all attributes of a class private/protected .
2). If a "non-callable" attribute is going to be used outside a class,
think about making it a property and name the property well, because
you never know...
"""



You use accessors when you need to control access to a data attribute.

Indeed. And when you don't need too ? (the second 'o' is not a typo)

Quote:
That's not advocacy, that's common sense.

I'm afraid we don't use the same definition of "common sense". Writing
useless code is not part of my definition of "common sense".

(snip)
Quote:

I agree. And I already told you I think in terms of state and behavior
and not language dependent semantics.

Then why do you advise "(making) all attributes of a class
private/protected" and systematically using properties ?



Because you don't want third parties illegimately tampering with an
object's internal data and thus crashing your system?

Let's try again...

point 1 : there's *no* language-inforced access restriction in Python.
Just a *convention*.

point 2 : so anyone *can* "illegimately tampering with an object's
internal data" at will.

point 3 : anyway it's not *my* system that will then crash - but the
system of the one who "illegimately" played with my package's objects
internals. And as far as I'm concerned, it's none of my problem - they
were marked as implementation, so anyone playing with them is on it's
own. FWIW, I suspect that if someone want to muck with implementation,
he certainly has a good legitimate reason to do so, and will do her best
to not break anything. Else he's a complete idiot and there's no cure
for this.

point 4 : since we have computed attributes, turning a "public data
attribute" (to use your idiom) into a "private/protected data attribute
with accessors" *without breaking the interface* is not even a non-brainer.

Now, please, can you explain the difference between :

class Complicated(object):
def __init__(self, data):
self.data = data
def _get_data(self):
return self._data
def _set_data(self, data):
self._data = data

and

class Pragmatic(object):
def __init__(self, data)
self.data = data


and find any *valid* reason to use the first solution instead of the
second ? ('that's what the book says' not being a valid reason).


--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb@xiludom.gro'.split('@')])"
Back to top
tobias@stud.cs.uit.no
*nix forums beginner


Joined: 06 Aug 2005
Posts: 3

PostPosted: Wed Jul 19, 2006 5:09 pm    Post subject: Re: Accessors in Python (getters and setters) Reply with quote

[ZeD]
Quote:
you mean sed :)

sed 's/oldName/newName/g' oldFile > newFile

I used to be a Perl programmer :-)

perl -i.bak -pe 's/oldName/newName/g' *

As said, this is risky as oldName can be used in other contexts.

--
Tobias Brox, 69°42'N, 18°57'E
Back to top
tobias@stud.cs.uit.no
*nix forums beginner


Joined: 06 Aug 2005
Posts: 3

PostPosted: Wed Jul 19, 2006 5:12 pm    Post subject: Re: Accessors in Python (getters and setters) Reply with quote

[Jason]
Quote:
Nothing like being forced to write getters and setters in C++/Java
before you feel like shooting your source code. Please don't bring
this code-rage into Python.

"Code generation" springs into my mind. IMO, if the code needs to be
generated, the language is not sufficiently advanced.

--
Tobias Brox, 69°42'N, 18°57'E
Back to top
bruno modulix
*nix forums Guru


Joined: 21 Feb 2005
Posts: 819

PostPosted: Wed Jul 19, 2006 5:13 pm    Post subject: Re: Accessors in Python (getters and setters) Reply with quote

mystilleef wrote:
Quote:
Bruno Desthuilliers wrote:

mystilleef wrote:

(snip)


Quote:
For example, a third party randomly changing
is_active, (which Python lets you do freely and easily)

Unless you make it a read-only property.


So you see the purpose of accessors then?

*where* did I say *anything* that could *possibly* be taken as me not
seeing the point of computed attributes ?

What I'm saying here is that it's totally useless to duplicate default
behaviour.



And who's doing that?


That's exactly what you recommended: "make all attributes
private/protected (...) If a data attribute might likely be an API,
think about controlling access to via "properties""


Quote:
from False to

True may crash your GUI.

And I'm not making this up. Things like this
do really happen depending on the whackyness of your toolkit. So
sometimes, it is my duty to protect the state of an object. Especially
if its state cannot afford to be corrupted rendering the system
unstable. And situations like this are found a plenty in event based
programming. Which is programming objects based almost entirely on
state and behavior. As you can see this has nothing to do with Python
vs Java's vs X's implementation of accessors and how using them sucks,
or how they aren't Pythonic. Some domains just require this stuff.

Properties *are* 'accessors'.


I never said they weren't.

Fine.

Now : in a language with support for computed attributes, direct
attribute access is the default r/w accessors.

Depends on your definition of accessors.

something that let me access an attribute.

Quote:
Otherwise 97% of languages
provide direct access to an object's data attributes.

But not 97% of languages provide support for computed attributes.

Quote:

One of the requirements for designing robust object systems is ensuring
the state of objects aren't easily contaminated.

"contaminated" ???


Make an object's state unreliable. See above example.

That's the word you choose that I find really strange.



What's strange about it. If an object's data attribute is supposed to
state that it is false when there are no mark objects in the buffer,
and a third party accidently incorrectly changes the attribute to state
it is True for whatever reasons, you essentially corrupt the objects
state and render the whole system "unreliable," or "buggy". What again
is difficult to grasp?

The choice of the word "contaminated".

Quote:

That "state" is the
objects data (read: stuff the object needs to do something "reliably").

Makes no sens to me.


is_active is an object's data,

class Obj(object):
# ....
@apply
def is_active():
def fget(self):
return (self.something and self.computeThis()) \
or self.otherCondition()
def fset(self, val):
raise ReadOnlyError()
def fdel(self):
raise UndeletableError()
return **locals()

According to *your* sayings, Obj.is_active is "behaviour"...

Not my saying. OO says so.


Chapter and verse, please ?

now :
class Obj(object):
def __init__(self):
self.is_active = False

Now, 'is_active' is state again ?

Quote:
And this is why many overzealous OO languages do "force" you to use
accessors.

The only languages I know that "force" you to use accessors are
Smalltalk and Ruby (and Ruby offers some syntactic sugar for 'default' -
ie r/w - accessors).



Add Eiffel to the list. Java/C++/C#/Ada all recommend it by convention.

Java/C++/C#/Ada all recommend it because they have no support for
computed attributes, which means that you cannot change implementation
without breaking the interface.


Quote:

It's not because they hate you or aren't aware of the

convenience of having direct access to an object's attributes. It's
just because these languages convenience/robustness ratios are
different.

I'm afraid it has very few to do with "robustness".


Your opinion.


what's the exact difference in "robustness" between:

class DreamItisRobust(object):
def __init__(self):
self._attr = 42
def get_attr(self):
return self._attr
def set_attr(self, attr):
self._attr = attr

and

class DontCare(object):
def __init__(self):
self.attr = 42


???

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb@xiludom.gro'.split('@')])"
Back to top
antroy@gmail.com
*nix forums addict


Joined: 24 May 2006
Posts: 52

PostPosted: Wed Jul 19, 2006 7:03 pm    Post subject: Re: Accessors in Python (getters and setters) Reply with quote

Ed Jensen wrote:

Quote:
where the compiler prevents you from accessing
private variables, but the runtime allows access to these very variables
via reflection?

Java does not allow access to private members via reflection.

Yes it does. You can call setAccessible(true) on the Method object to
override the privateness.
Back to top
Gerhard Fiedler
*nix forums beginner


Joined: 12 Jul 2006
Posts: 18

PostPosted: Wed Jul 19, 2006 7:03 pm    Post subject: Re: Accessors in Python (getters and setters) Reply with quote

On 2006-07-19 14:12:33, Tobias Brox wrote:

Quote:
"Code generation" springs into my mind. IMO, if the code needs to be
generated, the language is not sufficiently advanced.

Isn't that just a question of level? I'm sure there are editors that
generate Python class stubs, GUI builders that generate Python GUI
frameworks, and so on. Nothing needs to be generated, but some things are
more convenient to write (for some people; convenience is quite subjective)
using generators.

Gerhard
Back to top
Bruno Desthuilliers
*nix forums Guru


Joined: 03 Mar 2005
Posts: 360

PostPosted: Wed Jul 19, 2006 7:32 pm    Post subject: Re: Accessors in Python (getters and setters) Reply with quote

Tobias Brox a écrit :
Quote:
[Jason]

Nothing like being forced to write getters and setters in C++/Java
before you feel like shooting your source code. Please don't bring
this code-rage into Python.


"Code generation" springs into my mind. IMO, if the code needs to be
generated, the language is not sufficiently advanced.

OTOH, most decorators and metaclass hacking is somehow code generation -

but hopefully not at the source code level...
Back to top
Diez B. Roggisch
*nix forums Guru


Joined: 20 Feb 2005
Posts: 882

PostPosted: Wed Jul 19, 2006 9:52 pm    Post subject: Re: Accessors in Python (getters and setters) Reply with quote

Ed Jensen schrieb:
Quote:
Diez B. Roggisch <deets@nospam.web.de> wrote:
Ah, you mean like in JAVA

Java is not an acronym. That is: it's "Java", not "JAVA".

Now THAT was an important information RIGHT on topic.

Quote:
where the compiler prevents you from accessing
private variables, but the runtime allows access to these very variables
via reflection?

Java does not allow access to private members via reflection.

For somebody nitpicking on natural language usage to a non-native
speaker, you show an impressive lack of knowledge in the actual subject
discussed.

http://www.onjava.com/pub/a/onjava/2003/11/12/reflection.html


Diez
Back to top
danielx
*nix forums beginner


Joined: 18 Jul 2006
Posts: 8

PostPosted: Thu Jul 20, 2006 3:04 am    Post subject: Re: Accessors in Python (getters and setters) Reply with quote

Bruno Desthuilliers wrote:
Quote:
ZeD wrote:
Bruno Desthuilliers wrote:


I decided to change the name of an attribute. Problem is I've used the
attribute in several places spanning thousands of lines of code. If I
had encapsulated the attribute via an accessor, I wouldn't need to do
an unreliable and tedious search and replace

find and grep are usually mostly reliable for this kind of tasks.


you mean sed :)

No, I meant find and grep.

sed 's/oldName/newName/g' oldFile > newFile

Yeah, fine - as long as your pretty sure the same name is not used in
other contexts in any of the source files...

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb@xiludom.gro'.split('@')])"

I think that was the original point about find/replace: it can be
really hard to automate a name change, because changes might occur that
you didn't intend; whereas, doing things by hand lacks consistency.

My solution is to use emacs' query-replace (which you can invoke with
M-%). It will find quicly and accurately, but I ultimately hold the key
to whether something gets replaced or not.
Back to top
mystilleef@gmail.com
*nix forums beginner


Joined: 11 Oct 2005
Posts: 46

PostPosted: Thu Jul 20, 2006 4:50 am    Post subject: Re: Accessors in Python (getters and setters) Reply with quote

Bruno Desthuilliers wrote:
Quote:
mystilleef wrote:
Bruno Desthuilliers wrote:

mystilleef wrote:
(snip)

Of course using setters for the sake of just using them is pointless.

Indeed.



The reason to use them is if pre-conditions or post-conditions need to
be met. Or to control access to an objects states.

Then why advocate *systematic* use of them ?

(snip)

I never advocated anything.

You advocated
"""
1). Make all attributes of a class private/protected .
2). If a "non-callable" attribute is going to be used outside a class,
think about making it a property and name the property well, because
you never know...
"""



You use accessors when you need to control access to a data attribute.

Indeed. And when you don't need too ? (the second 'o' is not a typo)


You make the attribute private/protected.

Quote:
That's not advocacy, that's common sense.

I'm afraid we don't use the same definition of "common sense". Writing
useless code is not part of my definition of "common sense".

(snip)

I agree. And I already told you I think in terms of state and behavior
and not language dependent semantics.

Then why do you advise "(making) all attributes of a class
private/protected" and systematically using properties ?



Because you don't want third parties illegimately tampering with an
object's internal data and thus crashing your system?

Let's try again...

point 1 : there's *no* language-inforced access restriction in Python.
Just a *convention*.


Huh? What are properties for then?

Quote:
point 2 : so anyone *can* "illegimately tampering with an object's
internal data" at will.


And this is robust how?

Quote:
point 3 : anyway it's not *my* system that will then crash - but the
system of the one who "illegimately" played with my package's objects
internals. And as far as I'm concerned, it's none of my problem - they
were marked as implementation, so anyone playing with them is on it's
own. FWIW, I suspect that if someone want to muck with implementation,
he certainly has a good legitimate reason to do so, and will do her best
to not break anything. Else he's a complete idiot and there's no cure
for this.


You can't be serious. Please tell me you are joking.

Quote:
point 4 : since we have computed attributes, turning a "public data
attribute" (to use your idiom) into a "private/protected data attribute
with accessors" *without breaking the interface* is not even a non-brainer.

Now, please, can you explain the difference between :

class Complicated(object):
def __init__(self, data):
self.data = data
def _get_data(self):
return self._data
def _set_data(self, data):
self._data = data

and

class Pragmatic(object):
def __init__(self, data)
self.data = data


and find any *valid* reason to use the first solution instead of the
second ? ('that's what the book says' not being a valid reason).


I don't know it's your code not mine.

class Robust(object):

def __init__(self):
# Arbitrarily changing this state to False will crash app or will
# corrupt the whole event system.
self.__is_active = True

def get_is_active(self):
return self.__is_active

buffer_is_active = property(get_is_active, doc="True if buffer is
editable")

def monitor_events(self):
# Only methods of this class can change __is_active.
# Add code to change __is_active here.
return

See! I'm controlling access. Whee! And if one sober morning I want to
change the name __is_active to __buffer_is_active, I won't have to hunt
down 27000 lines of code to do it. Also a naive third party won't crash
my system by changing Robust's state arbitrarily. Because in the real
world when your program is buggy, you get bug reports, nasty emails
among other forms of ridicule. And your supposed solution to my problem
is me saying, "but...but...I told you not change is_active." Ha! And if
you can't figure out why anyone would do this, then I'm not wasting my
time here anymore. Someday you'll learn the hard way.

Thanks to the people who exposed me to Python's properties.

Bye
Back to top
mystilleef@gmail.com
*nix forums beginner


Joined: 11 Oct 2005
Posts: 46

PostPosted: Thu Jul 20, 2006 5:38 am    Post subject: Re: Accessors in Python (getters and setters) Reply with quote

Steve Holden wrote:
Quote:
mystilleef wrote, making me somewhat tired of his/her repeated inability
to get what's being said [sigh]:
Bruno Desthuilliers wrote:
mystilleef wrote:
Bruno Desthuilliers wrote:
mystilleef wrote:
Gerhard Fiedler wrote:
On 2006-07-15 06:55:14, mystilleef wrote:
In very well designed systems, the state of an object should only be
changed by the object.

IMO that's not quite true. Ultimately, the state always gets changed by
something else (user interaction, physical events); very few objects are
completely self-contained in their behavior.


Then in those cases the system becomes a victim of high coupling.

This makes it somewhat obvious that you don't appear to fully understand
the concept of coupling as applied to software systems.

Time to burn your book and face reality. ObjA sends message Msg1 to
ObjB. Part of the associated behaviour is that in responce to Msg1, objB
changes it's own state. Practical result : ObjB's state has been changed
by ObjA. Practical question : how do you hope to avoid this "hi
coupling" (lol), apart from making all your objects totally autistic ?

Are you serious?

Deadly serious. But I'm afraid you're still missing the point.

Well, you design an object that serves as a mediator.
All objects can then only interact with themselves and the mediator
only. Via signals, objects learn to automatically adjust their states
and respond to events.

signal -> message -> method call -> change state.

Spell it how you like, add as many indirection levels you want, it still
boils down to the fact that *something* triggers the state change.

Riiiiight!

If you implement an accessor to change a class's instances' states,
surely something has to call that accessor. You seem to be implying that
such calls can only be made from within other methods of the same
object, which (if true, which it isn't) would tend to leave each class
in a vacuum where nothing else can affect its instances.

Of *course* objects are subject to external influences: since you like
the concept of coupling, how else could different components be coupled
at all?

I gave the solution earlier. In well designed systems objects should be
responsible for updating their state themselves. In essence, objects
should learn to mind their own business. There will be some form of
coupling, but it should be minimal. Preferably the only coupling
permitted should be between an object and its mediator. Messages are
passed through the system via signals or events or established
protocols. What are the benefits? Well I can change the implementation
of any object at will without breaking the whole system. Or I can even
completely replace modules and objects with new ones without breaking
the whole system. If you are dealing with large source code, this is a
no brainer. And if you put a little effort into to it, you can create
objects that know when to initialize and destroy themselves as well as
update their states automatically. Welcome to event based programming.

(snip)

Quote:
I'm sure glad I didn't burn my book.

No comment.

In most systems (and you possibly have written some of them) are objects
whose state gets changed by other objects -- possibly through the
intermediation of setter methods that do nothing else but set the state.
There's no conceptual difference between directly setting the state or
calling a setter function that does nothing else but directly setting the
state -- except for one unnecessary level of indirection in the latter.

It depends. If certain conditions need to be met before changing the
state of an object, then arbitrarily changing it can be dangerous.

Does this imply a 'method call' *syntax* ?

That's language dependent.

Given the existence of
"computed attributes" (ie: support for 'attribute access' *syntax* with
hidden accessors) and the possibility to redefine implementation (from
default attribute r/w access to computed/controlled) without touching
the interface, why advocate the *systematic* use of computed attributes
when it's just duplicating the default behaviour ?

I'm not advocating anything.

cf below on this.

I'm just stating the use case for
accessors and the wisdom behind them. My qualm with implicit accessors
remains the name issue.

The "name issue" is *your* problem. And AFAICT, it's a "problem" because
you refuse to free your mind from a "what's in the book" mindset.

What book are we talking about?

Well you should know, you're the one who wants to hang on to it. So
please enlighten us, what is this source of knowledge that appears to
contradict sound computer science?


High coupling is bad. Exposing critical states of an object is bad. Any
decent computer science book will tell you that.

Quote:
For example, a third party randomly changing is_active, (which Python
lets you do freely and easily) from False to True may crash your GUI.
And I'm not making this up. Things like this do really happen depending
on the whackyness of your toolkit.

Whereas you appear to feel that there can be no possibility if a crash
because someone calls thing.is_active(True), and yet you repeatedly fail
to demonstrate the difference. Which is why this thread has been so
mind-numbingly long. As is pointed out AGAIN here:

That's quite true, but a setter that does nothing but change is_active
doesn't prevent this. If there is logic necessary to prevent state changes
in certain situations, this should be implemented. But whether you then
call this a part of the "behavior" (looking at the implementation as being
a setter method) or a part of the "state" (looking at the implementation as
being an added feature of the attribute) doesn't really make an objective
difference.

Of course using setters for the sake of just using them is pointless.

Indeed.

The reason to use them is if pre-conditions or post-conditions need to
be met. Or to control access to an objects states.

Then why advocate *systematic* use of them ?

(snip)

I never advocated anything.

You advocated
"""
1). Make all attributes of a class private/protected .
2). If a "non-callable" attribute is going to be used outside a class,
think about making it a property and name the property well, because
you never know...
"""

You use accessors when you need to control access to a data attribute.
That's not advocacy, that's common sense.

Perhaps so, but you still refuse to explain why it's better, when all
you need to do is read or write the value of an instance's attribute, to
define accessor methods to do it, introducing unnecessary (in Python)
overhead in the process.

Obviously if I want to control access to an attribute, it means I don't
want it altered or I want to perform pre/post conditional computations
before/after the attribute is accessed. There's a reason it is called
access control.

Quote:

State - behavior is not something I made up, so it isn't subjective.

The words (and the concept they describe) are not. Interpretation of
what is state and what is behaviour is subjective.

It
is a common term used in OO literature. In fact, the only reason I used
it is because I thought is was common knowledge.

It is.

Am I the only one here who has lost track of this "'tis/'tisn't" stuff?

And behaviors are not
just necessarily getters/setters, they are methods of objects.

Behaviour is how a given object reacts to a given message. *Nothing* in
this implies the notions of attributes or methods. Attributes and
methods are implementation details of the concepts of state and
behaviour, and - while this is a common implementation of OO concepts -
the choice to use non-callable attributes as representing the state
and callable ones as representing behaviour is totally
implementation-dependant.

I agree. And I already told you I think in terms of state and behavior
and not language dependent semantics.

Then why do you advise "(making) all attributes of a class
private/protected" and systematically using properties ?

Because you don't want third parties illegimately tampering with an
object's internal data and thus crashing your system?

In which case you write correct software and provide it with a thorough
set of tests to allow you to modify it without worrying too much about
breakage. Attribute access is part of an object's API just like method
calls are.


Or I use accessors. Because I write tests doesn't mean third parties do
so, or even uphold the practice.

Quote:
You seem to think that every ill in software design can be legislated
away by strangling design freedom with specific rules. I am afraid that
experience will teach you this is far from the case: go look at the way
that the "bondage" languages that use static typing (like Java and C++)
still fail to impose the required typing discipline on a determinedly
incompetent user.


Well I disagree. I used to share you mentality until I started managing
large source code. You need rules if you don't want your project to
collaspe under anarchy. And it is not until other people start using
your software in ways you never imagined that you realize the
importance of designing robust implementations upfront. When I wrote
less than a 1000 lines of Python code, I didn't care for
properties/accessors/public/private states or whatever. And I drank all
the Python philosophy cool aid I could get. But when you begin to get
emails about bugs in your software due to a third party inadvertently
changing states you never bothered to hide to begin with, then the
wisdom behind careful upfront planning begins to make sense.

Quote:
As has already been said, the Python philosophy is to provide the
features that "consenting adults" (i.e. programmers who know what they
are doing) can use most effectively to produce complex software systems
to reasonable deadlines. Unfortunately not all the knowledge required to
do this is readily available in books; the rest must come from experience.


That's all fine and dandy in the fantasy world. In the real world,
consenting adults do stupid things, and if I can prevent them from
doing it, especially when it affects me, I bloody well will.
Back to top
Dennis Lee Bieber
*nix forums Guru


Joined: 05 Mar 2005
Posts: 819

PostPosted: Thu Jul 20, 2006 5:43 am    Post subject: Re: Accessors in Python (getters and setters) Reply with quote

On Wed, 19 Jul 2006 18:54:55 +0200, Bruno Desthuilliers
<onurb@xiludom.gro> declaimed the following in comp.lang.python:

Quote:

Indeed. And when you don't need too ? (the second 'o' is not a typo)

Pardon, but for the sense you intend, it should be:


... don't need, too?

The "," is what allows for the "too" to have independent meaning ("also"
could have been use, and maybe with more emphasis:

... don't need, ALSO?

--
Wulfraed Dennis Lee Bieber KD6MOG
wlfraed@ix.netcom.com wulfraed@bestiaria.com
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: web-asst@bestiaria.com)
HTTP://www.bestiaria.com/
Back to top
Dennis Lee Bieber
*nix forums Guru


Joined: 05 Mar 2005
Posts: 819

PostPosted: Thu Jul 20, 2006 6:11 am    Post subject: Re: Accessors in Python (getters and setters) Reply with quote

On 19 Jul 2006 22:38:17 -0700, "mystilleef" <mystilleef@gmail.com>
declaimed the following in comp.lang.python:

Quote:

permitted should be between an object and its mediator. Messages are
passed through the system via signals or events or established
protocols. What are the benefits? Well I can change the implementation
of any object at will without breaking the whole system. Or I can even

Python permits that using properties... But one doesn't have to code
the properties from the get-go... Development can be done with direct
attribute access, and if it is determined that some sort of conditioning
logic is needed, it can be implemented WITHOUT CHANGING THE API.

This IS an "established protocol" in Python.
Quote:
High coupling is bad. Exposing critical states of an object is bad. Any
decent computer science book will tell you that.

In Python, using, if needed, properties, this is transparent... The

user of the object doesn't know, or need to know, if it is state or
behavior -- all it sees is that it supplies a value for something,
and/or retrieves a value for something.
Quote:

Obviously if I want to control access to an attribute, it means I don't
want it altered or I want to perform pre/post conditional computations
before/after the attribute is accessed. There's a reason it is called
access control.

Python properties support this, no need to have the user of the

object explicitly call a getter or setter...


Quote:
changing states you never bothered to hide to begin with, then the
wisdom behind careful upfront planning begins to make sense.

If it isn't part of the documented API, it is the user's fault. That

applies to all software...
--
Wulfraed Dennis Lee Bieber KD6MOG
wlfraed@ix.netcom.com wulfraed@bestiaria.com
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: web-asst@bestiaria.com)
HTTP://www.bestiaria.com/
Back to top
Marc 'BlackJack' Rintsch
*nix forums Guru Wannabe


Joined: 03 Mar 2005
Posts: 146

PostPosted: Thu Jul 20, 2006 6:55 am    Post subject: Re: Accessors in Python (getters and setters) Reply with quote

In <1153371049.561672.233550@h48g2000cwc.googlegroups.com>, mystilleef
wrote:

Quote:

Bruno Desthuilliers wrote:
mystilleef wrote:
Bruno Desthuilliers wrote:

Because you don't want third parties illegimately tampering with an
object's internal data and thus crashing your system?

Let's try again...

point 1 : there's *no* language-inforced access restriction in Python.
Just a *convention*.


Huh? What are properties for then?

To have a tool to change the default accessor into something more
complicated, a calculated attribute, without the need to change the API.

Quote:
point 2 : so anyone *can* "illegimately tampering with an object's
internal data" at will.


And this is robust how?

That's as robust as the consenting adults that use that code. And as
robust as Java where you can get at private attributes via reflection and
C++ where you can simply define private as public.

Quote:
point 3 : anyway it's not *my* system that will then crash - but the
system of the one who "illegimately" played with my package's objects
internals. And as far as I'm concerned, it's none of my problem - they
were marked as implementation, so anyone playing with them is on it's
own. FWIW, I suspect that if someone want to muck with implementation,
he certainly has a good legitimate reason to do so, and will do her best
to not break anything. Else he's a complete idiot and there's no cure
for this.


You can't be serious. Please tell me you are joking.

No he's not joking. If programmers don't read the "stop here, this is
internal" signs and carelessly change states then there's a much bigger
problem than access control. The problem is with the programmer, not the
language.

Quote:
point 4 : since we have computed attributes, turning a "public data
attribute" (to use your idiom) into a "private/protected data attribute
with accessors" *without breaking the interface* is not even a non-brainer.

Now, please, can you explain the difference between :

class Complicated(object):
def __init__(self, data):
self.data = data
def _get_data(self):
return self._data
def _set_data(self, data):
self._data = data

and

class Pragmatic(object):
def __init__(self, data)
self.data = data


and find any *valid* reason to use the first solution instead of the
second ? ('that's what the book says' not being a valid reason).


I don't know it's your code not mine.

class Robust(object):

def __init__(self):
# Arbitrarily changing this state to False will crash app or will
# corrupt the whole event system.
self.__is_active = True

def get_is_active(self):
return self.__is_active

buffer_is_active = property(get_is_active, doc="True if buffer is
editable")

def monitor_events(self):
# Only methods of this class can change __is_active.
# Add code to change __is_active here.
return

See! I'm controlling access. Whee!

No you don't.

obj = Robust()
obj._Robust__is_active = 42

The name munging is not meant to provide access control but to avoid name
clashes when dealing with deep inheritance hierarchies or mixin classes.

A pythonista would just call the attribute `_is_active` and rely on the
common sense of other programmers not to play with it at will.

Quote:
And if one sober morning I want to change the name __is_active to
__buffer_is_active, I won't have to hunt down 27000 lines of code to do
it.

If it's called `_is_active` then the access to it should not be spread
over 27000 lines. You don't access attributes not belonging to the API
from everywhere in the code base. If you do, you are a bit careless as a
programmer, don't you think?

Quote:
Also a naive third party won't crash my system by changing Robust's
state arbitrarily. Because in the real world when your program is buggy,
you get bug reports, nasty emails among other forms of ridicule. And
your supposed solution to my problem is me saying, "but...but...I told
you not change is_active."

The name `_is_active` tells that it's not API. If the naïve third party
does not respect this than it's on its own. The solution is indeed to
tell that to them because otherwise they will get into trouble when they
continue to program in Python where this is the common way to make things
"private".

Quote:
Ha! And if you can't figure out why anyone would do this, then I'm not
wasting my time here anymore. Someday you'll learn the hard way.

You shouldn't waste your time with Python then. The language is obviously
not "bondage" enough for your needs.

Ciao,
Marc 'BlackJack' Rintsch
Back to top
Google

Back to top
Display posts from previous:   
Post new topic   Reply to topic Page 6 of 8 [116 Posts] Goto page:  Previous  1, 2, 3, 4, 5, 6, 7, 8 Next
View previous topic :: View next topic
The time now is Sat Nov 22, 2008 7:56 am | All times are GMT
navigation Forum index » Programming » python
Jump to:  

Similar Topics
Topic Author Forum Replies Last Post
No new posts Python proficiency test Kent Johnson python 0 Fri Jul 21, 2006 10:47 am
No new posts Since there was talk of if-then-else not being allowed in... Casey Hawthorne python 5 Fri Jul 21, 2006 3:41 am
No new posts Using python code from Java? fortepianissimo python 4 Thu Jul 20, 2006 5:36 pm
No new posts FAQ 1.9 How does Perl compare with other languages like J... PerlFAQ Server Perl 0 Thu Jul 20, 2006 7:03 am
No new posts Depricated String Functions in Python Anoop python 14 Thu Jul 20, 2006 6:26 am

Computeach | Skateboarding | Myspace Layouts | Online Advertising | Car Loan
Copyright © 2004-2005 DeniX Solutions SRL
 
Other DeniX Solutions sites: Unix/Linux blog |  electronics forum |  medicine forum |  science forum | 
Privacy Policy


Powered by phpBB © 2001, 2005 phpBB Group
[ Time: 2.5590s ][ Queries: 16 (2.3059s) ][ GZIP on - Debug on ]