473,653 Members | 2,972 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

property() usage - is this as good as it gets?

Hi,

I want to manage and control access to several important attributes in
a class and override the behaviour of some of them in various
subclasses.

Below is a stripped version of how I've implemented this in my current
bit of work.

It works well enough, but I can't help feeling there a cleaner more
readable way of doing this (with less duplication, etc).

Is this as good as it gets or can this be refined and improved
especially if I was to add in a couple more attributes some fairly
complex over-ride logic?

#!/usr/bin/env python

class A(object):
def __init__(self):
self._x = None
self._y = None

def _set_x(self, value):
self._x = value

def _get_x(self):
return self._x

x = property(_get_x , _set_x)

def _set_y(self, value):
self._y = value

def _get_y(self):
return self._y

y = property(_get_y , _set_y)

class B(A):
def __init__(self):
self._z = None
super(B, self).__init__( )

def _set_x(self, x):
# An example subclass 'set' override.
if x == 10:
raise Exception('%r is invalid!' % x)
self._x = x

x = property(A._get _x, _set_x)

def _set_z(self, value):
self._z = value

def _get_z(self):
return self._z

z = property(_get_z , _set_z)

del A._get_x, A._set_x, A._get_y, A._set_y
del B._set_x, B._get_z, B._set_z
Aug 22 '08 #1
18 1636
On Aug 22, 11:18*am, David Moss <drk...@gmail.c omwrote:
Hi,

I want to manage and control access to several important attributes in
a class and override the behaviour of some of them in various
subclasses.

Below is a stripped version of how I've implemented this in my current
bit of work.

It works well enough, but I can't help feeling there a cleaner more
readable way of doing this (with less duplication, etc).

Is this as good as it gets or can this be refined and improved
especially if I was to add in a couple more attributes some fairly
complex over-ride logic?

#!/usr/bin/env python

class A(object):
* * def __init__(self):
* * * * self._x = None
* * * * self._y = None

* * def _set_x(self, value):
* * * * self._x = value

* * def _get_x(self):
* * * * return self._x

* * x = property(_get_x , _set_x)

* * def _set_y(self, value):
* * * * self._y = value

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

* * y = property(_get_y , _set_y)
Within the bounds of Python, that's it.

In the cases where you're not executing code on 'get' or 'set', it
might be possible to have a default getter/setter, that just sets the
value of a variable name. This keeps your interface the same across
inheritance and changes. Possible to have it assign a default value
too.

def _set_z(self, value):
self._z = value

#def _get_z(self):
# return self._z

z = property( True, _set_z ) #still gets self._z

Unless, you are looking at something 'periodic' or regular. From
something I'm working on:

def _getbalance( self ):
return self._tree.geti (
self.where+ self.lookup[ 'balance' ] )

def _getparent( self ):
return self._tree.getI (
self.where+ self.lookup[ 'parent' ] )

Where 'balance' and 'parent' could both come from something generic:

balance= property( tree_lookup( 'balance' ) )
parent= property( tree_lookup( 'parent' ) )

They would have to take care to define 'self' properly and everything.
Aug 22 '08 #2
On Fri, Aug 22, 2008 at 12:18 PM, David Moss <dr****@gmail.c omwrote:
Hi,

I want to manage and control access to several important attributes in
a class and override the behaviour of some of them in various
subclasses.

Below is a stripped version of how I've implemented this in my current
bit of work.

It works well enough, but I can't help feeling there a cleaner more
readable way of doing this (with less duplication, etc).
It could certainly be made more concise, without changing the meaning:

###

from operator import attrgetter
class attrsetter(obje ct):
def __init__(self, attr):
self._attr = attr
def __call__(self, object, value):
setattr(object, self._attr, value)
def defaultproperty (attr):
return property(attrge tter(attr), attrsetter(attr ))

class A(object):
def __init__(self):
self._x = None
self._y = None

x = defaultproperty ('_x')
y = defaultproperty ('_y')

class B(A):
def __init__(self):
super(B, self).__init__( )
self._z = None

def _set_x(self, x):
# An example subclass 'set' override.
if x == 10:
raise Exception('%r is invalid!' % x)
self._x = x

x = property(A.x.fg et, _set_x)
z = defaultproperty ('_z')
# You really don't need to do this, but you can if you want
del _set_x

###

But, given the example you gave, you could also write things this way
(aside from no longer forbidding deleting the properties, which really
shouldn't be necessary):

###

class A(object):
def __init__(self):
self.x = None
self.y = None

class B(A):
def __init__(self):
super(B, self).__init__( )
self._x = self.x
self.z = None

def _set_x(self, x):
# An example subclass 'set' override.
if x == 10:
raise Exception('%r is invalid!' % x)
self._x = x

x = property(attrge tter('_x'), _set_x)

###

It's difficult to know exactly what would work best for you without a
better idea of how your properties override each other.

-Miles
Aug 22 '08 #3
On Aug 22, 12:18 pm, David Moss <drk...@gmail.c omwrote:
Hi,

I want to manage and control access to several important attributes in
a class and override the behaviour of some of them in various
subclasses.

Below is a stripped version of how I've implemented this in my current
bit of work.

It works well enough, but I can't help feeling there a cleaner more
readable way of doing this (with less duplication, etc).

Is this as good as it gets or can this be refined and improved
especially if I was to add in a couple more attributes some fairly
complex over-ride logic?
A small improvement as far as overriding goes is the OProperty recipe:
http://infinitesque.ne t/articles/2005/enhancing%20Pyt hon's%20propert y.xhtml

George
Aug 22 '08 #4
David Moss wrote:
Hi,

I want to manage and control access to several important attributes in
a class and override the behaviour of some of them in various
subclasses.

Below is a stripped version of how I've implemented this in my current
bit of work.

It works well enough, but I can't help feeling there a cleaner more
readable way of doing this (with less duplication, etc).

Is this as good as it gets or can this be refined and improved
especially if I was to add in a couple more attributes some fairly
complex over-ride logic?
The extended property type in Python 2.6 makes it much easier to
overwrite the getter, sett or deleter of a property:

http://docs.python.org/dev/library/f...perty#property

class C(object):
def __init__(self): self._x = None

@property
def x(self):
"""I'm the 'x' property."""
return self._x

@x.setter
def x(self, value):
self._x = value

@x.deleter
def x(self):
del self._x

class D(C):
@C.x.getter
def x(self):
return 2 * self._x

@x.setter
def x(self, value):
self._x = value // 2

Christian

Aug 22 '08 #5
On Fri, Aug 22, 2008 at 1:49 PM, Miles <se*********@gm ail.comwrote:
from operator import attrgetter
class attrsetter(obje ct):
def __init__(self, attr):
self._attr = attr
def __call__(self, object, value):
setattr(object, self._attr, value)
This solution is very nice, but in programming is a good practice to be uniform:
The interface of "attrgetter " is "def attrgetter(*nam es): ..."
So, it will be nice the same for attrsetter: "def attrsetter(*nam es):"

I will send an example, but extending it a little bit and also using
some nice python structures of functional programming:

#<code>
from operator import attrgetter

def attrsetter(*nam es):
def closure(obj, *values):
for i in xrange(len(name s)):
setattr(obj, names[i], values[i])
return closure

attrmanager = lambda name: (attrgetter(nam e), attrsetter(name ))
class Test(object):
x = property(*attrm anager('_x'))
y = property(*attrm anager('_y'))

setvalues = attrsetter('x', 'y')
test = Test()

test.x = 1
print 'test.x:', test.x

test.y = 'Merchise'
print 'test.y:', test.y
# Just another test

test.setvalues( 3, 'med')

print 'test.x:', test.x
print 'test.y:', test.y
#</code>

Regards
Aug 22 '08 #6
On Aug 22, 11:18 am, David Moss <drk...@gmail.c omwrote:
Hi,

I want to manage and control access to several important attributes in
a class and override the behaviour of some of them in various
subclasses.

Below is a stripped version of how I've implemented this in my current
bit of work.

It works well enough, but I can't help feeling there a cleaner more
readable way of doing this (with less duplication, etc).

Is this as good as it gets or can this be refined and improved
especially if I was to add in a couple more attributes some fairly
complex over-ride logic?

#!/usr/bin/env python

class A(object):
def __init__(self):
self._x = None
self._y = None

def _set_x(self, value):
self._x = value

def _get_x(self):
return self._x

x = property(_get_x , _set_x)

def _set_y(self, value):
self._y = value

def _get_y(self):
return self._y

y = property(_get_y , _set_y)
To the OP: you have a unique procedure executed for every attribute of
an instance, for each of set, get, and del. That's a lot of code. If
you don't want unique procedures, what patterns should they follow?
What is wrong with the way you overrode 'get_x' above? When
brainstorming, don't restrict yourself to Python syntax-- make
something up, and we'll write Python.
Aug 24 '08 #7
castironpi <castiro...@gma il.comwrote:
and we'll write Python.
I haven't seen anything you've contributed to this group that would so
far be considered well-written Python.

Confusing and border-line insane, yes. Pythonic? Not at all.

Here's a tip: try actually developing some real-world application in
Python for a while, rather than the god-knows-what-you're-doing
attempts that you keep hijacking various threads with. Your code isn't
anywhere near as clever as you seem to think.
Aug 24 '08 #8
On Aug 22, 1:18*pm, David Moss <drk...@gmail.c omwrote:
It works well enough, but I can't help feeling there a cleaner more
readable way of doing this (with less duplication, etc).

Is this as good as it gets or can this be refined and improved
especially if I was to add in a couple more attributes some fairly
complex over-ride logic?

#!/usr/bin/env python

class A(object):
* * def __init__(self):
* * * * self._x = None
* * * * self._y = None

* * def _set_x(self, value):
* * * * self._x = value

* * def _get_x(self):
* * * * return self._x

* * x = property(_get_x , _set_x)

* * def _set_y(self, value):
* * * * self._y = value

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

* * y = property(_get_y , _set_y)

FWIW, there is a variant of property() that allows you to re-use the
same getter/setter code for multiple attributes:

http://code.activestate.com/recipes/205126/
Raymond Hettinger

Aug 24 '08 #9
On Aug 24, 5:00*am, alex23 <wuwe...@gmail. comwrote:
castironpi <castiro...@gma il.comwrote:
and we'll write Python.

I haven't seen anything you've contributed to this group that would so
far be considered well-written Python.

Confusing and border-line insane, yes. Pythonic? Not at all.

Here's a tip: try actually developing some real-world application in
Python for a while, rather than the god-knows-what-you're-doing
attempts that you keep hijacking various threads with. Your code isn't
anywhere near as clever as you seem to think.
Python isn't as clever as you think. It's a language. Do you want a
link to clever code? I like to encourage creativity.
Aug 24 '08 #10

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

Similar topics

0
546
by: Ronen | last post by:
Hi All, I am running a client against a web application installed on a remote server written in C# which involve infragistics for GUI . The .NET framework I use is from version 1.1.4322 and we use the following Infragistics components: * WebSchedule Component Version: 1.0.20033.6 * UltraWebTree and UltraWebMenu components Version: 3.0.20033.8 * UltraWebListbar component Version: 2.0.20033.8
4
2031
by: DraguVaso | last post by:
Hi, I'm having some weird behaviour, and I can't find any solution to this. I made a UserControl (uclCommands) which contains a Toolbar (ToolBar1) with Modifiers = Public. I put this usercontrol on my form and call it Ucl1. In the Property Window in the Windows Forms Designer I change Ucl1.ToolBar1.ButtonSize to a bigger value.
11
2474
by: Paulo Eduardo | last post by:
Hi, All! We are developing one app for windows 95/98/Me/NT4.0/2000/XP/2003 using Visual C++ 6.0. We need to set the % of CPU Usage to app process. Is there an API to set % of CPU Usage? Can Someone help us? Thanks in advance.
62
2980
by: djake | last post by:
Someone can explain me why to use property get and property set to access a value in a class, insted of access the value directly? What's the usefulness of property statements in VB.NET? Thanks
35
5491
by: Alex Martelli | last post by:
Having fixed a memory leak (not the leak of a Python reference, some other stuff I wasn't properly freeing in certain cases) in a C-coded extension I maintain, I need a way to test that the leak is indeed fixed. Being in a hurry, I originally used a q&d hack...: if sys.platform in ('linux2', 'darwin'): def _memsize(): """ this function tries to return a measurement of how much memory this process is consuming, in some arbitrary unit...
2
2459
by: jld | last post by:
Hi, I developed an asp.net based eCommerce Website for a client and it is hosted at discount asp. The site is quite interactive, queries a database a lot and uses ajax.asp.net to spice up interactivity. The service suffers from a lot of restarts since discountasp enforces a 100mb per worker thread limit and when you top it, the service gets restarted. When there is a lot of traffic on the site, this happens
104
5199
by: jayapal | last post by:
Hi all, Whenever I use the gets() function, the gnu c compiler gives a warning that it is dangerous to use gets(). why...? regards, jayapal.
2
2332
by: Sin Jeong-hun | last post by:
In short, is there any way to know the very code that is currently hogging the CPU? I've written an application which continously GETting web pages using HttpWebRequest's asynchronous methods (it only GETs responses (BegingGetResponse,EndGetResponse), not reads the stream contents). I've read articles about asynchronous request operations. I aborted timed out requests based on the article. ( http://www.developerfusion.co.uk/show/4654/ )...
0
8283
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
8811
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
8704
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
8470
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,...
1
6160
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
5620
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();...
1
2707
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1914
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1591
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.