473,626 Members | 3,320 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

object.attribut e vs. object.getAttri bute()

For the past 6-8 months, I've spent most of my time writing C++ and a
little bit of Java. Both of these languages support and encourage the
use of private data and explicit accessor functions, i.e. instead of
writing x = foo.bar, you write x = foo.getBar(). Now that I'm back to
writing Python, I find myself in a quandry.

Historically, I've always avoided accessor functions and just reached
directly into objects to get the value of their attributes. Since
Python doesn't have private data, there really isn't much advantage to
writing accessors, but somehow I'm now finding that it just feels wrong
not to. I'm not sure if this feeling is just a C++/Java-ism that will
cure itself with time, or if perhaps it really does make sense and I
should change the way I code.

On the plus side, accessors/mutators give me:

1) Implicit documentation of which attributes I intended to be part of
an object's externally visible state (accessors).
2) Hooks to do data checking or invarient assertions (mutators).
3) Decoupling classes by hiding the details of data structures.
4) Vague feeling that I'm doing a good thing by being more in line with
mainstream OO practices :-)

On the minus side:

1) More typing (which implies more reading, which I think reduces the
readability of the finished product).
2) Need to write (and test) all those silly little functions.
3) Performance hit due to function call overhead.
4) Only the appearance of private data (modulo some slots hackery).
5) Code is harder to change (adding functionality means going back and
adding more slots).
6) Vague feeling that I'm dirtying myself by letting C++ and Java change
my Python coding habits :-)

Comments?
Jul 18 '05 #1
8 9984
I've always disliked accessor methods in C++ and Java. I can understand the
reason for using them, but they are just so ugly.

Danger: Advice from a Python newbie follows... :-)

My suggestion would be to use Python properties, as defined with the
property() function that was added in 2.2. Best of both worlds: You get the
clean syntax of directly reading and writing properties just as if they were
attributes, but behind the scenes you've defined get/set/del functions for
each property.

Personally, I wouldn't define properties for everything--I would use
ordinary attributes wherever they do the job. The beauty is that you can
always replace an attribute with a property without having to change the
calling code--which eliminates most of the reason for using accessor methods
as you would in C++.

-Mike

Roy Smith wrote:
For the past 6-8 months, I've spent most of my time writing C++ and a
little bit of Java. Both of these languages support and encourage the
use of private data and explicit accessor functions, i.e. instead of
writing x = foo.bar, you write x = foo.getBar(). Now that I'm back to
writing Python, I find myself in a quandry.

Historically, I've always avoided accessor functions and just reached
directly into objects to get the value of their attributes. Since
Python doesn't have private data, there really isn't much advantage to
writing accessors, but somehow I'm now finding that it just feels wrong
not to. I'm not sure if this feeling is just a C++/Java-ism that will
cure itself with time, or if perhaps it really does make sense and I
should change the way I code.

On the plus side, accessors/mutators give me:

1) Implicit documentation of which attributes I intended to be part of
an object's externally visible state (accessors).
2) Hooks to do data checking or invarient assertions (mutators).
3) Decoupling classes by hiding the details of data structures.
4) Vague feeling that I'm doing a good thing by being more in line with
mainstream OO practices :-)

On the minus side:

1) More typing (which implies more reading, which I think reduces the
readability of the finished product).
2) Need to write (and test) all those silly little functions.
3) Performance hit due to function call overhead.
4) Only the appearance of private data (modulo some slots hackery).
5) Code is harder to change (adding functionality means going back and
adding more slots).
6) Vague feeling that I'm dirtying myself by letting C++ and Java change
my Python coding habits :-)

Comments?

Jul 18 '05 #2
On Mon, Sep 15, 2003 at 08:29:10PM -0400, Roy Smith wrote:
For the past 6-8 months, I've spent most of my time writing C++ and a
little bit of Java. Both of these languages support and encourage the
use of private data and explicit accessor functions, i.e. instead of
writing x = foo.bar, you write x = foo.getBar(). Now that I'm back to
writing Python, I find myself in a quandry.

Historically, I've always avoided accessor functions and just reached
directly into objects to get the value of their attributes. Since
Python doesn't have private data, there really isn't much advantage to
writing accessors, but somehow I'm now finding that it just feels wrong
not to. I'm not sure if this feeling is just a C++/Java-ism that will
cure itself with time, or if perhaps it really does make sense and I
should change the way I code.


Write your python code naturally, using 'x = foo.bar'. Derive all your
classes from 'object' (use new-style classes). If you ever need
to do something "behind the scenes", you can switch to using "property",
and have a function automatically called on attribute read, write, and
delete---and it even documents itself:

class C(object):
def __init__(self):
self._y = 0

def get_x(self):
return self._y * self._y

def set_x(self, val):
self._y = val

def del_x(self):
raise TypeError, "Cannot delete attribute"

x = property(get_x, set_x, del_x,
"A stupid attribute that squares itself"
"... and won't go away")
from roy import C
c = C()
c.x = 3
print c.x 9 del c.x
del c.x Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/tmp/roy.py", line 12, in del_x
raise TypeError, "Cannot delete attribute"
TypeError: Cannot delete attribute help(C)

[...]
| ----------------------------------------------------------------------
| Properties defined here:
|
| x
| A stupid attribute that squares itself... and won't go away
[...]

Jeff

Jul 18 '05 #3
Roy Smith <ro*@panix.co m> wrote previously:
|1) Implicit documentation of which attributes I intended to be part of
|an object's externally visible state (accessors).

Some attribute names start with an underscore. Those are the ones that
are NOT intended to be part of the external interface.

|2) Hooks to do data checking or invarient assertions (mutators).

Yep, you need accessors (or properties) to do this.

|3) Decoupling classes by hiding the details of data structures.

Initial underscores again.

|4) Vague feeling that I'm doing a good thing by being more in line with
|mainstream OO practices :-)

If you want to be mainstream, use VB. But accessors are not IMO a
requirement for "proper" OOP.

Yours, Lulu...

--
_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/
_/_/ ~~~~~~~~~~~~~~~ ~~~~~[me***@gnosis.cx]~~~~~~~~~~~~~~~ ~~~~~~ _/_/
_/_/ The opinions expressed here must be those of my employer... _/_/
_/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them! _/_/
Jul 18 '05 #4

"Roy Smith" <ro*@panix.co m> wrote in message
news:ro******** *************** @reader2.panix. com...
For the past 6-8 months, I've spent most of my time writing C++ and a
little bit of Java. Both of these languages support and encourage the
use of private data and explicit accessor functions, i.e. instead of
writing x = foo.bar, you write x = foo.getBar(). Now that I'm back to
writing Python, I find myself in a quandry.

Historically, I've always avoided accessor functions and just reached
directly into objects to get the value of their attributes. Since
Python doesn't have private data, there really isn't much advantage to
writing accessors, but somehow I'm now finding that it just feels wrong
not to. I'm not sure if this feeling is just a C++/Java-ism that will
cure itself with time, or if perhaps it really does make sense and I
should change the way I code.
I'm with Jeff on this one. If it looks like a value, then access it
directly.
If you need to slide a mutator in under it, it's simple enough to make
it a property later without affecting any of the code that uses it.

On the plus side, accessors/mutators give me:

1) Implicit documentation of which attributes I intended to be part of
an object's externally visible state (accessors).
Use the underscore convention.
2) Hooks to do data checking or invarient assertions (mutators).
3) Decoupling classes by hiding the details of data structures.
4) Vague feeling that I'm doing a good thing by being more in line with
mainstream OO practices :-)
4 is actually the same thing as 3, except not stated as cleanly.
On the minus side:

1) More typing (which implies more reading, which I think reduces the
readability of the finished product).
2) Need to write (and test) all those silly little functions.
3) Performance hit due to function call overhead.
4) Only the appearance of private data (modulo some slots hackery).
5) Code is harder to change (adding functionality means going back and
adding more slots).
6) Vague feeling that I'm dirtying myself by letting C++ and Java change
my Python coding habits :-)
Items 1 through 3 don't matter if you use properties. You use them when
you need them, otherwise you simply access the attribute directly.

If you're using Python, you don't worry about private data. Use the
underscore convention, and don't worry otherwise.

Don't use slots.

I never worry about where a good idea comes from.

John Roth
Comments?

Jul 18 '05 #5
Hi Roy:
I'm not sure if this feeling is just a C++/Java-ism that will
cure itself with time, or if perhaps it really does make sense and I
should change the way I code.
If you're not sure, I suggest you err on the side of caution. To me caution
means writting less code, not more. And this isn't really an either-or
proposition. One of the best things about properties is that clients can't
easily distinguish them from normal attribute access. Nothing stops you
from starting with simple attributes and then later changing them to
properties later.
6) Vague feeling that I'm dirtying myself by letting C++ and Java change
my Python coding habits :-)


This need not be vague. I have that feeling concretely when thinking of
Java.

-troy
Jul 18 '05 #6

Read this nice article "Why getter and setter methods are evil: Make
your code more maintainable by avoiding accessors"

http://www.javaworld.com/javaworld/j...5-toolbox.html

"Roy Smith" <ro*@panix.co m> escribió en el mensaje
news:ro******** *************** @reader2.panix. com...
For the past 6-8 months, I've spent most of my time writing C++ and a
little bit of Java. Both of these languages support and encourage the
use of private data and explicit accessor functions, i.e. instead of
writing x = foo.bar, you write x = foo.getBar(). Now that I'm back to
writing Python, I find myself in a quandry.

Historically, I've always avoided accessor functions and just reached
directly into objects to get the value of their attributes. Since
Python doesn't have private data, there really isn't much advantage to
writing accessors, but somehow I'm now finding that it just feels wrong not to. I'm not sure if this feeling is just a C++/Java-ism that will
cure itself with time, or if perhaps it really does make sense and I
should change the way I code.

On the plus side, accessors/mutators give me:

1) Implicit documentation of which attributes I intended to be part of
an object's externally visible state (accessors).
2) Hooks to do data checking or invarient assertions (mutators).
3) Decoupling classes by hiding the details of data structures.
4) Vague feeling that I'm doing a good thing by being more in line with mainstream OO practices :-)

On the minus side:

1) More typing (which implies more reading, which I think reduces the
readability of the finished product).
2) Need to write (and test) all those silly little functions.
3) Performance hit due to function call overhead.
4) Only the appearance of private data (modulo some slots hackery).
5) Code is harder to change (adding functionality means going back and
adding more slots).
6) Vague feeling that I'm dirtying myself by letting C++ and Java change my Python coding habits :-)

Comments?

Jul 18 '05 #7
Hi.

"Roy Smith" <ro*@panix.co m> wrote in message
news:ro******** *************** @reader2.panix. com...
[snip]
1) More typing (which implies more reading, which I think reduces the
readability of the finished product).
2) Need to write (and test) all those silly little functions.


If you only intend to create simple properties[*], then the following recipe
may address issues 1) and 2) (except for the testing part):

http://aspn.activestate.com/ASPN/Coo.../Recipe/157768

If you're going to create more complex properties, you may find this
recipe(idiom) of interest:

http://aspn.activestate.com/ASPN/Coo.../Recipe/205183
Hope that's useful,
Sean
[*] By "simple properties", I mean something like the following:

''' assume we're inside a class definition
and self.__foo has been initialized.
'''
def get_foo(self):
return self.__foo
def set_foo(self, value):
self.__foo = value
def del_foo(self):
del self.__foo
foo = property(fget=g et_foo, fset=set_foo, fdel=del_foo, doc="foo")

Jul 18 '05 #8
Aurelio Martin Massoni wrote:
Read this nice article "Why getter and setter methods are evil: Make
your code more maintainable by avoiding accessors"

http://www.javaworld.com/javaworld/j...5-toolbox.html


That's an interesting article. Be sure to read the comments at the end of
page 3--the real fun starts there!

-Mike
Jul 18 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

18
3033
by: Steven Bethard | last post by:
In the "empty classes as c structs?" thread, we've been talking in some detail about my proposed "generic objects" PEP. Based on a number of suggestions, I'm thinking more and more that instead of a single collections type, I should be proposing a new "namespaces" module instead. Some of my reasons: (1) Namespace is feeling less and less like a collection to me. Even though it's still intended as a data-only structure, the use cases...
12
4943
by: Stefano | last post by:
Hi all, what is the correct use of the "default" attribute in XML Schema? For example: <xs:element name="myProperty" type="xs:string" default="myDefaultValue"/> What can I do with it? What is the meaning of < ....default="myDefaultValue" /> ?
3
9368
by: Carl Lindmark | last post by:
*Cross-posting from microsoft.public.dotnet.languages.csharp, since I believe the question is better suited in this XML group* Hello all, I'm having some problems understanding all the ins and outs with datasets and datatables (and navigating through the filled datatable)... Just when I thought I had gotten the hang of it, another problem arose: I can't seem to access the "xsi:type" attribute. That is, the XML file looks
4
3939
by: Robert Strickland | last post by:
I have a service that I call that returns back a XmlNode type. I need to get to an attribute value and would like to use the GetAttribute method (because it takes a string). However, XmlNode (or XmlElement) does not have that method. They have the attributes collection with the item method that takes an number value performing an ordinal lookup. I can declare an Xml document, load the returning Xml stream, and then use the method but I do...
1
4025
by: Gustaf | last post by:
My docs have attributes called "order", with a default value of 1. So if there is no "order" attribute, the program shall use the value 1. Implementing this with XmlTextReader was harder than expected. Since GetAttribute() returns null if the attribute isn't found, and null can be interpreted as false, I thought this would do it: decimal order = 1; if (r.GetAttribute("order")) order = Convert.ToDecimal(r.GetAttribute("order"));
35
2283
by: eyoung | last post by:
I call a function that takes the unit price and quantity ordered to create an amount...it looks something like this. function calculateCost() { quantity=document.RFO.quantity.value; unitPrice=document.RFO.unitPrice.value; total=0; if(isPositiveInteger(quantity)) {
1
1028
by: Stedak | last post by:
We have a WinForm application that we would like to add security to. We would also like to set up a configuration utility that would make it easier to assign or remove rights. When using code access security is there a way to create a list of functions/classes that have a security attribute assigned to them? i.e a new module is added. In the assembly there are certain items that can be added or removed from specific groups. What are...
2
5665
by: SM | last post by:
Hello, I've created this 'wonderful' function the embeds a youtube video in a specified div section using the Javascript DOM. Everything works OK... until I realize how bad the logical programming was. See, if you look at the function below, everytime i passed the youtube video id, i create the object over and over and over .... again and again and again..... you get the picture. I could erase the object using and created again, but...
3
1929
by: Mike | last post by:
Hello, I'm trying the following code: function MoveTeam(id){ This works-gets the value of the element var x=document.getElementById(id).innerHTML; This doesnt get the value of the alpha attribute of the same element. I get a js error. var q=document.getElementByID(id).attribute('alpha') alert (q)
0
8199
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8638
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8365
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8505
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6125
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5574
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4198
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1811
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1511
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.