473,796 Members | 2,505 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Externally-defined properties?

Frankly, I was surprised this worked at all, but I tried
creating a property outside of a class (i.e. at the module
level), and it seems to behave as a property:
def get_x(ob): .... global x
.... return str(x)
.... def set_x(ob, value): .... global x
.... x = int(value)
.... def del_x(ob): .... global x
.... del x
.... def x_access(): .... return property(get_x, set_x, del_x, "X defined externally?")
....
class Accessor(object ): .... s_x = x_access()
.... def __str__(self):
.... print "Accessor has x = %s" % self.s_X
.... a = Accessor()
a.s_x = 3
a.s_x '3' dir() ['Accessor', '__builtins__', '__doc__', '__name__', 'a', 'del_x', 'get_x', 'p', 'set_x', 'x', 'x_access'] x

3

(of course in the real example, x will probably be in an
entirely different module, used as a library -- the client code
just calls a function to get a property that is automatically
managed for it).

So far, the only problem I see is that it only works if the
property is assigned to a new-type class attribute (otherwise,
the first assignment simply replaces the property).

I'm thinking of using this to tie a property of a class to an
external data source (a joystick axis, in fact -- or at least
its last-polled value).

There is a more convential way to do this, of course -- I could
just use a "get_value" function, but there is something attractive
about have a variable that is simply bound to the external
data source like this. It seems like a good way to encapsulate
functionality that I don't really want the high level class to
have to "think" about.

I mention it here, because I've never seen a property used
this way. So I'm either being very clever, or very dumb,
and I would be interested in opinions on which applies. ;-)

Am I about to shoot myself in the foot?

Cheers,
Terry

--
Terry Hancock ( hancock at anansispacework s.com )
Anansi Spaceworks http://www.anansispaceworks.com

Aug 24 '05 #1
3 1236
On Wed, 24 Aug 2005 01:15:03 -0500, Terry Hancock <ha*****@anansi spaceworks.com> wrote:
Frankly, I was surprised this worked at all, but I tried
creating a property outside of a class (i.e. at the module
level), and it seems to behave as a property:
def get_x(ob):... global x
... return str(x)
... def set_x(ob, value):... global x
... x = int(value)
... def del_x(ob):... global x
... del x
... def x_access():... return property(get_x, set_x, del_x, "X defined externally?")
...
class Accessor(object ):... s_x = x_access()
... def __str__(self):
... print "Accessor has x = %s" % self.s_X
... a = Accessor()
a.s_x = 3
a.s_x'3' dir()['Accessor', '__builtins__', '__doc__', '__name__', 'a', 'del_x', 'get_x', 'p', 'set_x', 'x', 'x_access'] x3

(of course in the real example, x will probably be in an
entirely different module, used as a library -- the client code
just calls a function to get a property that is automatically
managed for it).

So far, the only problem I see is that it only works if the
property is assigned to a new-type class attribute (otherwise,
the first assignment simply replaces the property).

I'm thinking of using this to tie a property of a class to an
external data source (a joystick axis, in fact -- or at least
its last-polled value).

There is a more convential way to do this, of course -- I could
just use a "get_value" function, but there is something attractive
about have a variable that is simply bound to the external
data source like this. It seems like a good way to encapsulate
functionalit y that I don't really want the high level class to
have to "think" about.

I mention it here, because I've never seen a property used
this way. So I'm either being very clever, or very dumb,
and I would be interested in opinions on which applies. ;-)

Am I about to shoot myself in the foot?

ISTM you are basically exploiting your freedom to define the getter/setter/deleter
functions of a property any way you please. Another way, if you just want a proxy
object whose property attributes access designated other objects' attributes, you
could use a custom descriptor class, e.g.,
class Indirect(object ): ... def __init__(self, tgtattr, tgtobj):
... self.tgtattr = tgtattr
... self.tgtobj = tgtobj
... def __get__(self, inst, cls=None):
... if inst is None: return self
... return getattr(self.tg tobj, self.tgtattr)
... def __set__(self, inst, value):
... setattr(self.tg tobj, self.tgtattr, value)
... def __delete__(self , inst):
... delattr(self.tg tobj, self.tgtattr)
...

A place to put properties: class Accessor(object ): pass ...

An example object to access indirectly class Obj(object): pass ... obj = Obj()
Making Accessor instance attribute 'xobj' access 'obj' attribute of Obj instance obj Accessor.xobj = Indirect('obj', obj)
An Accessor instance to use for the property attribute magic a = Accessor()
Set obj.obj = 123 indirectly a.xobj = 123
Check vars(obj) {'obj': 123}

Set up access to an object attribute in a different module import sys
Accessor.sin = Indirect('stdin ', sys)
a.sin <open file '<stdin>', mode 'r' at 0x02E8E020>
Accessor.pi = Indirect('pi', __import__('mat h'))
a.pi 3.1415926535897 931 a.pi = 3
a.pi 3 import math
math.pi

3

I'd say there's possibilities for shooting yourself in the foot. Maybe passing
a code to Indirect to enable get/set/del selectively would help.
Regards,
Bengt Richter
Aug 24 '05 #2
Terry Hancock wrote:
Frankly, I was surprised this worked at all, but I tried
creating a property outside of a class (i.e. at the module
level), and it seems to behave as a property:
Not so surprising. Making a class begins by making a little namespace,
then using it to build the class. If you look at how class construction
works, it gets handed the namespace to wrap parts (the originals are
left alone). After playing with your example for a little, perhaps
the following will illustrate things:

def get_x(obj):
return thevar

def set_x(obj, val):
global thevar
thevar = val

def del_x(obj):
global thevar
del thevar

def textify(obj):
objid = '%s_%s' % (obj.__class__. __name__, id(obj))
try:
return '%s:%r' % (objid, thevar)
except (NameError, AttributeError) :
return '%s:---' % objid

prop = property(get_x, set_x, del_x)

class One(object):
x = prop
__repr__ = textify

class Two(object):
y = prop
__str__ = textify

Class Three(object):
__repr__ = textify

a = One()
b = Two()
c = Three()
print a, b, c
a.x = 5
print a.x, b.y, a, b, c
Three.z = One.x
print c, c.z
del b.y
print a, b, c
print a.x

You may want to raise AttributeError on get_x (you have no name to use):
def get_x(obj):
try:
return thevar
except NameError:
raise AttributeError
Am I about to shoot myself in the foot?


Well, usually all this playing is good for understanding how Python
works, but makes your connections less than explicit, and we know
that explicit is better than implicit.

--Scott David Daniels
Sc***********@A cm.Org
Aug 24 '05 #3
Well, I have used factories of properties external to the class many
times,
and they work pretty well.

Michele Simionato

Aug 25 '05 #4

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

Similar topics

2
2077
by: Marc | last post by:
Hi all, I have a problem with managing the interchange between COM/Excel and Python if the user closes the workbook externally. Everything works fine as long as the user only uses the exit keys I've provided to close the Excel apps and COM interfaces. But I really need the ability to manage the workbook if someone closes it using the 'exit' command or the right/upper 'x' from within the excel spreadsheet.
2
287
by: John A. Janes | last post by:
Here's an odd one, I'm currently developing a site for internal usage, to get around their public website, I set the internal server to port 8080 (I publish my .net from my office externally). There is no problem at all accessing the site externally, but it is almost impossible to access internally. I checked to make sure I have no references in the site to the external publishing address. This may be a very simple problem, but one I...
7
1477
by: Paul Kirby | last post by:
Hello All I am writing an application and a dll file and I was wondering how I would access functions within the exe file from the dll? Example: /* EXE File */ long GetUserCount(void) {
3
3276
by: pwh777 | last post by:
I have three databases. DB1 has a button on a form. When I click that button, I want to import all the objects from DB2 to DB3 (just as you would if you would chose the File > Get External Data > Import menu option). Then I want to Compact and Repair DB3. I want to do this all by pushing the button in DB1. Is this possible?
16
1941
w33nie
by: w33nie | last post by:
I really have no idea where to start for this, as i'm VERY new to scripting, but i do have intermediate skills at html, so i thought i'd try and get a nudge in the right direction from a help site. I'm currently making a website where I'll need to have a rankings table of teams for an online computer game league. I'll put this table in my .htm file, as I want it to be integrated in the page, and look just like a regular table would. but, I...
3
1398
by: =?Utf-8?B?TWlrZQ==?= | last post by:
Hi. In VB.NET, is it possible to determine whether an ASP.NET is being accessed internally (within the same domain hosting the application) or externally (across the internet)? I've looked at using the HttpRequest.ServerVariables Property, but it doesn't look like it's NameValueCollection contains any items which would identify whether or not a program is being accessed internally/externally. Basically I need to apply certain logic...
3
3400
by: Shawn T | last post by:
I have an application with a page that has a web user control When I call that page that has this user control, locally (http:// localhost/ApplicationX/default.aspx) and also externally ie (http:// <webserver>/ApplicationX/default.aspx), the display is all different. For example, a text box shows with border on one and textbox shows as label in the other. I am suspecting that it might be CSS issue. I checked the CSS file and everything...
3
1216
by: Spam Catcher | last post by:
Is there a way to externally add items to ASP.NET's data cache? Any sort of APIs in .NET? I have a Windows forms program which may need to add some items. Or I guess I could just call a webpage. Hmm. -- spamhoneypot@rogers.com (Do not e-mail)
3
1052
by: King | last post by:
This is a new test for object persistency. I am trying to store the relationship between instances externally. It's not working as expected. May be I am doing it in wrong way. Any suggestions? import shelve class attrib(object): pass
1
1638
by: donovant | last post by:
HI There, We have an in-house vb.net/C# application which basically serves as a database front end. The application was initially desgned primarily for in-house use only, however recently the apllication is being by a few users working from home, and they have come accross a few issues which did not occur when they used the application in the office. The main issue is that the batch report generator function of the application generates...
0
9680
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
10456
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
10230
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...
0
6788
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
5442
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5575
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4118
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
2
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2926
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.