473,326 Members | 2,061 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Best way to control assignment to attribute?

Hi all

I want to control the assignment of a value to an attribute. Instead
of allowing it to be changed directly, I want to enforce that a method
is called, which will perform the assignment subject to various
checks.

From reading the manuals, this is one way to do it.

class frank:
def __init__(self,x):
self.setval_x(x)

def __setattr__(self,name,value):
if name == 'x':
raise 'cannot change value of x - use setval_x(value)'
else:
self.__dict__[name] = value

def setval_x(self,value):
ok = 1
# perform any checks required
if ok:
self.__dict__['x'] = value

Is this the best way, or does anyone have any other suggestions?

I notice that an application can beat this by using the __dict__
syntax itself. Is there any way to prevent this? Just curious, it is
not a major concern.

Any comments will be appreciated.

Thanks

Frank Millman
Jul 18 '05 #1
7 1218
Frank Millman wrote:
Hi all

I want to control the assignment of a value to an attribute. Instead
of allowing it to be changed directly, I want to enforce that a method
is called, which will perform the assignment subject to various
checks.

From reading the manuals, this is one way to do it.

class frank:
def __init__(self,x):
self.setval_x(x)

def __setattr__(self,name,value):
if name == 'x':
raise 'cannot change value of x - use setval_x(value)'
I think you shouldn't use string exceptions in new code anymore.
else:
self.__dict__[name] = value

def setval_x(self,value):
ok = 1
# perform any checks required
if ok:
self.__dict__['x'] = value

Is this the best way, or does anyone have any other suggestions?

I notice that an application can beat this by using the __dict__
syntax itself. Is there any way to prevent this? Just curious, it is
not a major concern.

Any comments will be appreciated.

Thanks

Frank Millman


Use new style classes and properties:
class Frank(object): .... def __init__(self, x):
.... self.x = x
.... def getX(self):
.... return self._x
.... def setX(self, x):
.... if x < 0:
.... raise ValueError("x must be >= 0")
.... self._x = x
.... x = property(getX, setX)
.... f = Frank(3)
f.x = 2
f.x = -2

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 8, in setX
ValueError: x must be >= 0

The main advantage is cleaner code, which will become more obvious as the
number of special attributes increases. Also, checked and normal attribute
access is transparent to the client.

Peter

Jul 18 '05 #2
Frank Millman wrote:
I want to control the assignment of a value to an attribute. Instead
of allowing it to be changed directly, I want to enforce that a method
is called, which will perform the assignment subject to various
checks.


I think it is possible with new-style classes, introduced in Python 2.2.

http://users.rcn.com/python/download/Descriptor.htm
http://www.python.org/2.2.2/descrintro.html

Gerrit.

--
PrePEP: Builtin path type
http://people.nl.linux.org/~gerrit/c.../pep-xxxx.html
Asperger's Syndrome - a personal approach:
http://people.nl.linux.org/~gerrit/english/

Jul 18 '05 #3
Frank,
See __slots__; not sure if there's a newer/better way.

wes

Frank Millman wrote:
Hi all

I want to control the assignment of a value to an attribute. Instead
of allowing it to be changed directly, I want to enforce that a method
is called, which will perform the assignment subject to various
checks.

From reading the manuals, this is one way to do it.

class frank:
def __init__(self,x):
self.setval_x(x)

def __setattr__(self,name,value):
if name == 'x':
raise 'cannot change value of x - use setval_x(value)'
else:
self.__dict__[name] = value

def setval_x(self,value):
ok = 1
# perform any checks required
if ok:
self.__dict__['x'] = value

Is this the best way, or does anyone have any other suggestions?

I notice that an application can beat this by using the __dict__
syntax itself. Is there any way to prevent this? Just curious, it is
not a major concern.

Any comments will be appreciated.

Thanks

Frank Millman


Jul 18 '05 #4
In article <XF**********************@bgtnsc05-news.ops.worldnet.att.net>,
wes weston <ww*****@att.net> wrote:
Frank Millman wrote:

I want to control the assignment of a value to an attribute. Instead
of allowing it to be changed directly, I want to enforce that a method
is called, which will perform the assignment subject to various
checks.


See __slots__; not sure if there's a newer/better way.


You should be certain before even thinking of suggesting __slots__.
__slots__ is intended only to save memory; there are many problems with
using it if you don't know what you're doing.
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"The joy of coding Python should be in seeing short, concise, readable
classes that express a lot of action in a small amount of clear code --
not in reams of trivial code that bores the reader to death." --GvR
Jul 18 '05 #5
Aahz,
He might be more interested in naming his class vars
with two leading underscores. eh? This mangles the name
making it not as it appears in the text and not accessible
by the expressed name. Does not the __slots__ statement
keep "you" from creating a new unintended class var?
wes

Aahz wrote:
In article <XF**********************@bgtnsc05-news.ops.worldnet.att.net>,
wes weston <ww*****@att.net> wrote:
Frank Millman wrote:
I want to control the assignment of a value to an attribute. Instead
of allowing it to be changed directly, I want to enforce that a method
is called, which will perform the assignment subject to various
checks.


See __slots__; not sure if there's a newer/better way.

You should be certain before even thinking of suggesting __slots__.
__slots__ is intended only to save memory; there are many problems with
using it if you don't know what you're doing.


Jul 18 '05 #6
Wes, please don't top-post. Consider the following:

A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet?

In article <vX*********************@bgtnsc04-news.ops.worldnet.att.net>,
wes weston <ww*****@att.net> wrote:
Aahz wrote:
In article <XF**********************@bgtnsc05-news.ops.worldnet.att.net>,
wes weston <ww*****@att.net> wrote:
Frank Millman wrote:

I want to control the assignment of a value to an attribute. Instead
of allowing it to be changed directly, I want to enforce that a method
is called, which will perform the assignment subject to various
checks.

See __slots__; not sure if there's a newer/better way.


You should be certain before even thinking of suggesting __slots__.
__slots__ is intended only to save memory; there are many problems with
using it if you don't know what you're doing.


He might be more interested in naming his class vars with two leading
underscores. eh? This mangles the name making it not as it appears
in the text and not accessible by the expressed name. Does not the
__slots__ statement keep "you" from creating a new unintended class
var?


Two leading underscores would be good, but it doesn't directly solve the
problem about controlling access to the attribute. Yes, __slots__
prevents the creation of unintended attributes, but it also has other --
frequently undesirable -- consequences. I encourage you to look up some
of the old threads in Google.
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"The joy of coding Python should be in seeing short, concise, readable
classes that express a lot of action in a small amount of clear code --
not in reams of trivial code that bores the reader to death." --GvR
Jul 18 '05 #7
fr***@chagford.com (Frank Millman) wrote:
Hi all

I want to control the assignment of a value to an attribute. Instead
of allowing it to be changed directly, I want to enforce that a method
is called, which will perform the assignment subject to various
checks.


Thanks to everybody for the replies. Clearly property() is the way to
go.

I have avoided new-style classes up to now, as I was waiting for a
real need to use them. Now I have one, so it is time to roll up my
sleeves and get stuck in.

Thanks again.

Frank
Jul 18 '05 #8

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

Similar topics

166
by: Graham | last post by:
This has to do with class variables and instances variables. Given the following: <code> class _class: var = 0 #rest of the class
1
by: Green | last post by:
Hi, I have a question concerning how to manipulate the properties in the user control, and there is an interesting article about this from Microsoft:...
8
by: Neil.Jin | last post by:
>>> class A: .... i = 1 .... >>> a = A() >>> A.i 1 >>> a.i 1 >>> A.i = 2 >>> A.i
35
by: nagy | last post by:
I do the following. First create lists x,y,z. Then add an element to x using the augumented assignment operator. This causes all the other lists to be changed also. But if I use the assignment...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.