473,804 Members | 2,123 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

accessor/mutator functions

When I look at how classes are set up in other languages (e.g. C++), I
often observe the following patterns:
1) for each data member, the class will have an accessor member
function (a Get<whatever> function)
2) for each data member, the class will have a mutator member function
(a Set<whatver> function)
3) data members are never referenced directly; they are always
referenced with the accessor and mutator functions

My questions are:
a) Are the three things above considered pythonic?
b) What are the tradeoffs of using getattr() and setattr() rather than
creating accessor and mutator functions for each data member?

Jul 18 '05 #1
22 6794
mi************@ yahoo.com wrote:
When I look at how classes are set up in other languages (e.g. C++), I
often observe the following patterns:
1) for each data member, the class will have an accessor member
function (a Get<whatever> function)
2) for each data member, the class will have a mutator member function
(a Set<whatver> function)
3) data members are never referenced directly; they are always
referenced with the accessor and mutator functions

My questions are:
a) Are the three things above considered pythonic?
No
b) What are the tradeoffs of using getattr() and setattr() rather than
creating accessor and mutator functions for each data member?


Use property descriptors instead:
http://www.python.org/2.2.1/descrintro.html#property
http://users.rcn.com/python/download...htm#properties

Michael

Jul 18 '05 #2
> My questions are:
a) Are the three things above considered pythonic?


Python uses a function called 'property to achieve the same effect.
This example is taken from the documentation:

class C(object):
def __init__(self):
self.__x = 0
def getx(self):
return self.__x
def setx(self, x):
if x < 0: x = 0
self.__x = x
x = property(getx, setx)
In the above example, "C().x" would invoke and return the result of
..getx (the accessor), and "C().x = 10" would invoke .setx (the
mutator).

Are they considered Pythonic? Well, It depends on how they are used.
If you are using properties to perform some kind of type checking...
then the answer is probably No.

I've found that they are quite useful for implementing lazy evaluation
of attributes, which I would consider quite Pythonic.

Sw.
Jul 18 '05 #3
If the class had two attributes--x and y--would the code look like
something lik this:

class C(object):
def __init__(self):
self.__x = 0
self.__y = 0
def getx(self):
return self.__x
def setx(self, x):
if x < 0: x = 0
self.__x = x
def gety(self):
return self.__y
def sety(self, y):
if y < 0: y = 0
self.__y = y
x = property(getx, setx)
y = property(gety, sety)

?

Because if so, does the term 'lazy evaluation' refer to the fact that
instead of:

C().getx()
C().gety()
C().setx(10)
C().sety(10)

one would substitute:

C().x
C().y
C().x = 10
C().y = 10

?

Jul 18 '05 #4
> Because if so, does the term 'lazy evaluation' refer to the fact that
instead of:


No, it is a common technical term. It means that a value is computed the
time it is requested for the first time.

Like this:

class Foo(object):

def __init__(self):
self.__bar = None

def getBar(self):
if self.__bar is None:
self.__bar = some_lengthy_co mputation()
return self.__bar
That you can make bar a property of Foo is unrelated to this.

Another reason to use properties is if the value is always or at least
frequently a freshly computed one.
--
Regards,

Diez B. Roggisch
Jul 18 '05 #5

<mi************ @yahoo.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
When I look at how classes are set up in other languages (e.g. C++), I
often observe the following patterns:
1) for each data member, the class will have an accessor member
function (a Get<whatever> function)
2) for each data member, the class will have a mutator member function
(a Set<whatver> function)
3) data members are never referenced directly; they are always
referenced with the accessor and mutator functions

My questions are:
a) Are the three things above considered pythonic?
As others have said, 'no', as in 'unnecessary because we have a better way
to accomplish the same purpose without doubling the attribute namespace'.
The purpose of the pattern is to hide the specific implementation of a
class (which attributes are static and which dynamic) and to allow that
implementation to change without changing programs that use the class.
Consider a complex class with interdependent .real, .imag, .rad, and .theta
attributes and the possible behind-the-scene implementations for what is
kept static and how they are kept synchronized. The need for get/set to
accomplish this in C++ arises from the fact that attribute names are
resolved at compile time, so that x.a syntax can only be used for simple
static attributes and access. Python, on the other hand, has means to
'magically' map what looks like direct attribute access into a function
call. First there was __get/setattr__ (which is awkward for multiple
dynamic attributes) and now properties with get/set/del for individual
dynamic attributes.
b) What are the tradeoffs of using getattr() and setattr() rather than
creating accessor and mutator functions for each data member?

--
http://mail.python.org/mailman/listinfo/python-list


Jul 18 '05 #6
mi************@ yahoo.com wrote:
If the class had two attributes--x and y--would the code look like
something lik this:

class C(object):
def __init__(self):
self.__x = 0
self.__y = 0
def getx(self):
return self.__x
def setx(self, x):
if x < 0: x = 0
self.__x = x
def gety(self):
return self.__y
def sety(self, y):
if y < 0: y = 0
self.__y = y
x = property(getx, setx)
y = property(gety, sety)


It could do - that works. One feature of this solution is that it leaves the
accessor/mutator functions in the namespace. That may be a good or a bad thing.
If bad, you could simply delete them after the property call (which is
probably better written as close as possible to the functions)

i.e., class C(object):
def __init__(self):
self.__x = 0
self.__y = 0
def getx(self):
return self.__x
def setx(self, x):
if x < 0: x = 0
self.__x = x
x = property(getx, setx)
del getx, setx
def gety(self):
return self.__y
def sety(self, y):
if y < 0: y = 0
self.__y = y
y = property(gety, sety)
del gety, sety

There are also recipes in the cookbook for defining property "suites" more elegantly

Note, that it is also easy to "roll your own" descriptor, which may be
worthwhile if you have a lot of similar properties, for example (not tested
beyond what you see):

from weakref import WeakKeyDictiona ry

class Property(object ):
def __init__(self, adapter):
"""adapter is a single argument function that will be
applied to the value before setting it"""
self.objdict = WeakKeyDictiona ry()
self.adapter = adapter
def __get__(self, obj, cls):
if isinstance(obj, cls):
return self.objdict[obj]
else:
return self
def __set__(self, obj, value):
self.objdict[obj] = self.adapter(va lue)

class C(object):
x = Property(lambda val: max(val, 0))
y = Property(lambda val: val%2)
z = Property(abs)
c= C()
c.x = -3
c.x 0 c.y = -3
c.y 1 c.z = -3
c.z 3

Michael

Jul 18 '05 #7
Michael Spencer <ma**@telcopart ners.com> wrote:
mi************@ yahoo.com wrote:
When I look at how classes are set up in other languages (e.g. C++), I
often observe the following patterns:
1) for each data member, the class will have an accessor member
function (a Get<whatever> function)
2) for each data member, the class will have a mutator member function
(a Set<whatver> function)
3) data members are never referenced directly; they are always
referenced with the accessor and mutator functions

My questions are:
a) Are the three things above considered pythonic?


No
b) What are the tradeoffs of using getattr() and setattr() rather than
creating accessor and mutator functions for each data member?


Use property descriptors instead:
http://www.python.org/2.2.1/descrintro.html#property
http://users.rcn.com/python/download...htm#properties


Actually I would say just access the attribute directly for both get
and set, until it needs to do something special in which case use
property().

The reason why people fill their code up with boiler plate get/set
methods is to give them the flexibility to change the implementation
without having to change any of the users. In python you just swap
from direct attribute access to using property().

Also note that with property() you can make an attribute read only (by
defining only the get method) which is often the encapsulation you
really want - and that is something you can't do in C++.

--
Nick Craig-Wood <ni**@craig-wood.com> -- http://www.craig-wood.com/nick
Jul 18 '05 #8
On 28 Feb 2005 10:30:03 GMT,
Nick Craig-Wood <ni**@craig-wood.com> wrote:
Actually I would say just access the attribute directly for both get
and set, until it needs to do something special in which case use
property(). The reason why people fill their code up with boiler plate get/set
methods is to give them the flexibility to change the implementation
without having to change any of the users. In python you just swap
from direct attribute access to using property().


The reason their code is so inflexible is that they've filled their
classes with boiler plate get/set methods.

Why do users of classes need such access anyway? If my class performs
useful functions and returns useful results, no user of my class should
care about its attributes. If I "have to" allow access to my attributes
in order that my users be happy, then I did something else wrong when I
designed the class and its public interface in the first place.

I usually aim for this: if users of the public interface of my class
can figure out that I changed the implementation, then I've exposed too
much. Sure there are exceptions, but that's my basic thought process.

Sorry about the rant.

Regards,
Dan

--
Dan Sommers
<http://www.tombstoneze ro.net/dan/>
μ₀ × ε₀ × c² = 1
Jul 18 '05 #9

mi************@ yahoo.com wrote:
When I look at how classes are set up in other languages (e.g. C++), I often observe the following patterns:
1) for each data member, the class will have an accessor member
function (a Get<whatever> function)
2) for each data member, the class will have a mutator member function (a Set<whatver> function)
3) data members are never referenced directly; they are always
referenced with the accessor and mutator functions

My questions are:
a) Are the three things above considered pythonic?
No. It's not good programming practice in C++, either.

If you have a class that's nothing but a big data structure, you ought
to use it as a data structure. Writing accessor and mutator methods
for its fields is just doing a lot of work to accomplish nothing.

If you want to provide access to a certain occasional field, but you're
concerned about keeping the interface backwards-compatible, go ahead
and use them. But try to observe the following rules of thumb:

1. Don't provide accessor or mutator function to every single member of
every single class you write. Only provide accessor/mutator functions
if the accessor/mutator methods are a sensible and useful part of the
class's interface.

2. Don't think of these methods as accessors or mutators. Instead,
think
of them as methods that access or mutate a certain abstract property of
the object that happens to be represented by a single member.

And, keep in mind that, since Python doesn't really have private data,
you don't have to worry about adding these functions to make debugging
easier.

b) What are the tradeoffs of using getattr() and setattr() rather than creating accessor and mutator functions for each data member?


Don't use getattr and setattr unless you have to construct the name of
the attribute at run time. That's what they're for.
--
CARL BANKS

Jul 18 '05 #10

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

Similar topics

6
2006
by: jerrygarciuh | last post by:
Hello, I have been working for some time now on a PHP OOP database abstraction layer. Yes I know there are others out there which are maturing but I like reinventing this wheel. The task I have at hand is that I want to specify 'has a' and 'has many' relationships in an array for each class and use these to automagically create the accessor methods and perhaps mutator methods as well.
2
2069
by: Todd A. Anderson | last post by:
I've inherited two "C++" code bases that I have to tie together and both of them make frequest use of public member variables in spite of all the information saying this limits flexibility. Well, their lack of foresight has bit me of course! I'd like to start off by converting all their public member variable accesses to the use of accessor methods. Then, I can reimplement selected accessor methods to provide the necessary glue between...
22
12042
by: Generic Usenet Account | last post by:
A lot has been said in this newsgroup regarding the "evil" set/get accessor methods. Arthur Riel, (of Vanguard Training), in his class, "Heuristis for O-O Analysis & Design", says that there is almost never an excuse for accessor methods. Personally, I do not go that far. I do feel that they serve a useful purpose (albeit in a limited manner). Personally I prefer dropping the "set" and "get" prefixes from the method names altogether. ...
3
4552
by: LuCk | last post by:
Can someone explain what these really are for example: ---------------------------------------------------------- void SetFrameRate(int iFrameRate) { m_iFrameDelay = 1000 / iFrameRate; }; ---------------------------------------------------------- I know what functions are and i know what void is and stuff but i dont get the whole `Accessor Methods` term i guess.
10
2253
by: ma740988 | last post by:
I'm hoping my post here doesn't fall into the 'hard to say' category, nonetheless I've been advised that multiple uses of accessor/mutator (get/set) member functions can be viewed as a 'design flaw'. In that regard I'm trying to create an 'example' class that's an alternative to the accessor/mutator approach. To further describe the problem consider the class BAR (below) which has a member data in_use that FOO needs visibility into. ...
10
356
by: Mikhail Teterin | last post by:
Hello! Consider the following simple accessor function: šššššššštypedefšstructš{ ššššššššššššššššintššššši; ššššššššššššššššcharššššname; šššššššš}šMY_TYPE; ššššššššconstšcharš*
0
9715
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9595
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
10600
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10097
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
7642
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
6867
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
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3835
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3002
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.