473,418 Members | 2,079 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,418 software developers and data experts.

Attribute monitoring in a class

Hi list:

I have googled quite a bit on this matter and I can't seem to find what
I need (I think Im just looking where I'm not suppose to :). I'm
working with code that is not of my authorship and there is a class
attribute that is changes by directly referencing it (object.attr =
value) instead of using a getter/setter (object.setAttr(Value) )
function. The thing is that I have no idea when the change occurs and I
would REALLY like to find out.
So here comes my question .....
Is there a function construct inside a python class that is
automatically called when an attr is changed????
Like for example

/class Class:
def __init__();
self.attr = "whatever"

def __attrChangeFunction__():
print "It has changed"

obj = Class()
obj.attr = "other whatever"

*Output:*
It has changed

/
Thanks for the help.
Regards/
/
Mar 14 '07 #1
5 1314
Joel Andres Granados a écrit :
Hi list:

I have googled quite a bit on this matter and I can't seem to find what
I need (I think Im just looking where I'm not suppose to :). I'm
working with code that is not of my authorship and there is a class
attribute that is changes by directly referencing it (object.attr =
value) instead of using a getter/setter (object.setAttr(Value) )
Which is the right thing to do in Python (I mean : *not* using
Java-style getters/setters).
function. The thing is that I have no idea when the change occurs and I
would REALLY like to find out.
So here comes my question .....
Is there a function construct inside a python class that is
automatically called when an attr is changed????
yes : object.__setattr__(self, name, value)

# example:
class Class(object):
def __init__();
self.attr = "whatever"

def __setattr__(self, name, value):
object.__setattr__(self, name, value)
if name == 'attr':
print "It has changed"
# you can also print the call frame,
# or set a 'hard' breakpoint here...

obj = Class()
obj.attr = "other whatever"

*Output:*
It has changed
Or you might turn attr into a property:

class Class(object):
def __init__();
self.attr = "whatever"

@apply
def attr():
def fset(self, value):
self._attr = value
print "It has changed"
def fget(self):
return self._attr
return property(**locals())

But unless you have other needs than simple tracing/debugging, it's
probably overkill.

HTH
Mar 14 '07 #2
Joel Andres Granados a écrit :
Hi list:

I have googled quite a bit on this matter and I can't seem to find what
I need (I think Im just looking where I'm not suppose to :). I'm
working with code that is not of my authorship and there is a class
attribute that is changes by directly referencing it (object.attr =
value) instead of using a getter/setter (object.setAttr(Value) )
function. The thing is that I have no idea when the change occurs and I
would REALLY like to find out.
So here comes my question .....
Is there a function construct inside a python class that is
automatically called when an attr is changed????
Like for example

/class Class:
def __init__();
self.attr = "whatever"

def __attrChangeFunction__():
print "It has changed"
Use a property. Extract from Python 2.3 docs:
"""
property( [fget[, fset[, fdel[, doc]]]])
Return a property attribute for new-style classes (classes that
derive from object).

fget is a function for getting an attribute value, likewise fset is
a function for setting, and fdel a function for del'ing, an attribute.
Typical use is to define a managed attribute x:

class C(object):
def getx(self): return self.__x
def setx(self, value): self.__x = value
def delx(self): del self.__x
x = property(getx, setx, delx, "I'm the 'x' property.")

New in version 2.2.
"""
obj = Class()
obj.attr = "other whatever"

*Output:*
It has changed

/
Thanks for the help.
Regards/
/
A+

Laurent.
Mar 14 '07 #3
Bruno Desthuilliers wrote:
Joel Andres Granados a écrit :
>Hi list:

I have googled quite a bit on this matter and I can't seem to find what
I need (I think Im just looking where I'm not suppose to :). I'm
working with code that is not of my authorship and there is a class
attribute that is changes by directly referencing it (object.attr =
value) instead of using a getter/setter (object.setAttr(Value) )

Which is the right thing to do in Python (I mean : *not* using
Java-style getters/setters).

>function. The thing is that I have no idea when the change occurs and I
would REALLY like to find out.
So here comes my question .....
Is there a function construct inside a python class that is
automatically called when an attr is changed????

yes : object.__setattr__(self, name, value)

# example:
class Class(object):
def __init__();
self.attr = "whatever"

def __setattr__(self, name, value):
object.__setattr__(self, name, value)
if name == 'attr':
print "It has changed"
# you can also print the call frame,
# or set a 'hard' breakpoint here...

obj = Class()
obj.attr = "other whatever"

*Output:*
It has changed

I used this ^^^^^^^^^^^^^^^ one. Thank for the help.
Works like a charm.
Regards
Or you might turn attr into a property:

class Class(object):
def __init__();
self.attr = "whatever"

@apply
def attr():
def fset(self, value):
self._attr = value
print "It has changed"
def fget(self):
return self._attr
return property(**locals())

But unless you have other needs than simple tracing/debugging, it's
probably overkill.

HTH
Mar 14 '07 #4
En Wed, 14 Mar 2007 10:01:54 -0300, Joel Andres Granados
<jo***********@gmail.comescribió:
Bruno Desthuilliers wrote:
>Joel Andres Granados a écrit :
>>I'm
working with code that is not of my authorship and there is a class
attribute that is changes by directly referencing it (object.attr =
value) instead of using a getter/setter (object.setAttr(Value) )
>yes : object.__setattr__(self, name, value)
I used this ^^^^^^^^^^^^^^^ one. Thank for the help.
The problem with __setattr__ is that it slows down significantly *all*
attributes.
Yours is the typical case when it's good to switch from using simple
attributes to using properties. See
<http://dirtsimple.org/2004/12/python-is-not-java.html>

--
Gabriel Genellina

Mar 14 '07 #5
Gabriel Genellina a écrit :
En Wed, 14 Mar 2007 10:01:54 -0300, Joel Andres Granados
<jo***********@gmail.comescribió:
>Bruno Desthuilliers wrote:
>>Joel Andres Granados a écrit :
>>>I'm
working with code that is not of my authorship and there is a class
attribute that is changes by directly referencing it (object.attr =
value) instead of using a getter/setter (object.setAttr(Value) )
>>yes : object.__setattr__(self, name, value)
I used this ^^^^^^^^^^^^^^^ one. Thank for the help.

The problem with __setattr__ is that it slows down significantly *all*
attributes.
Yours is the typical case when it's good to switch from using simple
attributes to using properties.
If this has to become a feature of the class, yes, indeed. If it's just
a temporary hack for debugging, the using the __getattr__ hook is
quicker and less intrusive.

Mar 15 '07 #6

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

Similar topics

7
by: svilen | last post by:
hello again. i'm now into using python instead of another language(s) for describing structures of data, including names, structure, type-checks, conversions, value-validations, metadata etc....
6
by: Randal | last post by:
Does anyone have a code sample of how one would "listen" to a TCP/IP session between an application on the local machine and a remote host. I'm looking for code that would allow me to specify a...
4
by: johnm | last post by:
Hello, We currently are running a CRM application that uses DB/2 7.2 for the data repository. We will be upgrading to 8.2 later this year....maybe....time and resources permitting. The...
0
by: Paul Steele | last post by:
I am working in a C# program what monitors the activity on a computer. I have been able to accomplish quite a bit so far, but one item I have not been able to figure out is if there is a way to...
3
by: JSheble | last post by:
I have a windows service that in the OnStart it creates a thread and runs a loop forever and ever, assuming the service is running. The loop stops during the OnStop event, and everything works...
9
by: Tim D | last post by:
Hi, I originally posted this as a reply to a rather old thread in dotnet.framework.general and didn't get any response. I thought it might be more relevant here; anyone got any ideas? My...
0
by: developer | last post by:
I am trying to get a custom provider to receive health monitoring events in vb.net, whidbey beta 1. I have a health monitoring setup like this in my web.config: <healthMonitoring enabled="true">...
6
by: Adam Donahue | last post by:
As an exercise I'm attempting to write a metaclass that causes an exception to be thrown whenever a user tries to access 'attributes' (in the traditional sense) via a direct reference. Consider:...
18
by: Gabriel Rossetti | last post by:
Hello everyone, I had read somewhere that it is preferred to use self.__class__.attribute over ClassName.attribute to access class (aka static) attributes. I had done this and it seamed to work,...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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,...
0
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...
0
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...
0
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...
0
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...

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.