473,772 Members | 2,510 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

switching an instance variable between a property and a normal value

I'd like to be able to have an instance variable that can sometimes be
accessed as a property, and sometimes as a regular value, e.g. something
like:

py> class C(object):
.... def usevalue(self, x):
.... self.x = x
.... def usefunc(self, func, *args, **kwds):
.... self._func, self._args, self._kwds = func, args, kwds
.... self.x = C._x
.... def _get(self):
.... return self._func(*sel f._args, **self._kwds)
.... _x = property(_get)
....
py> c = C()
py> c.usevalue(4)
py> c.x
4
py> c.usefunc(list)
py> c.x # I'd like this to print []
<property object at 0x04166DA0>

Of course, the code above doesn't do what I want because C._x is a
property object, so the assignment to self.x in usefunc just adds
another name for that property object. If I use self._x (or
getattr(self, '_x'), etc.) then self._func only gets called that one time:

py> class C(object):
.... def usevalue(self, x):
.... self.x = x
.... def usefunc(self, func, *args, **kwds):
.... self._func, self._args, self._kwds = func, args, kwds
.... self.x = self._x
.... def _get(self):
.... return self._func(*sel f._args, **self._kwds)
.... _x = property(_get)
....
py> c = C()
py> c.usefunc(list)
py> c.x is c.x # I'd like this to be False
True

Is there any way to get the kind of behavior I'm looking for? That is,
is there any way to make self.x use the property magic only some of the
time?

Steve

P.S. Yes, I know I could make both access paths run through the
property magic, with code that looks something like:

py> class C(object):
.... _undefined = object
.... def __init__(self):
.... self._value, self._func = C._undefined, C._undefined
.... def usevalue(self, x):
.... self._value = x
.... self._func = C._undefined
.... def usefunc(self, func, *args, **kwds):
.... self._func, self._args, self._kwds = func, args, kwds
.... self._value = C._undefined
.... def _get(self):
.... if self._value is not C._undefined:
.... return self._value
.... if self._func is not C._undefined:
.... return self._func(*sel f._args, **self._kwds)
.... raise AttributeError( 'x')
.... x = property(_get)
....
py> c = C()
py> c.usevalue(4)
py> c.x
4
py> c.usefunc(list)
py> c.x is c.x
False

This code is kinda complicated though because I have to make sure that
only one of self._func and self._value is defined at any given time.
Jul 18 '05 #1
1 1137
Steven Bethard wrote:
I'd like to be able to have an instance variable that can sometimes be
accessed as a property, and sometimes as a regular value, e.g. something
like:


If you want the behaviour to be switchable per-instance, you have to go the
route of always running through the property machinery, since property() creates
a descriptor on the class, not the instance.

On the other hand, if you want to switch the behaviour of every instance, then
making usevalue and usefunc class methods may give you some mileage.

I'm rather curious about your use case, though. . .

Here's a different way of using the property machinery, too:

Py> class C(object):
.... def __init__(self):
.... self._use_val = None
.... def useval(self, x):
.... self._val = x
.... self._use_val = True
.... def usefunc(self, func, *args, **kwds):
.... self._func, self._args, self._kwds = (func, args, kwds)
.... def _get(self):
.... use_val = self._use_val
.... if use_val is None:
.... raise AttributeError( 'x')
.... if use_val:
.... return self._val
.... else:
.... return self._func(*sel f._args, **self._kwds)
.... x = property(_get)
....
Py> c = C()
Py> c.useval(4)
Py> c.x
4
Py> c.usefunc(list)
Py> c.x
[]

--
Nick Coghlan | nc******@email. com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #2

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

Similar topics

6
22535
by: Martin | last post by:
I'd like to be able to get the name of an object instance from within a call to a method of that same object. Is this at all possible? The example below works by passing in the name of the object instance (in this case 'myDog'). Of course it would be better if I could somehow know from within write() that the name of the object instance was 'myDog' without having to pass it as a parameter. //////////////////////////////// function...
3
1507
by: DraguVaso | last post by:
Hi, I'm having the following situation: - A class clsFournisseur with public property's which raise a MyPropertyChanged-event in the Set-method for each Property. Public Event NomChanged As EventHandler Public Property Nom() As String Get Return m_strNom
7
6625
by: Baski | last post by:
Base class: class AssetBase { string _clli; public string CLLI { get
22
1600
by: WXS | last post by:
Sometimes a method in a class requires the use of class instance variables/fields that will not be used outside of the method itself. Currently this means you must create a instance field in the class such that from a maintenance stand point it is disconnected from the method, and also affords the opportunity for other methods to mess with the variable when they never should. For example: public class MyClass
4
1614
by: Angel Mateos | last post by:
Is posible something like this? public Class Class1 property readonly InstanceName get return me.InstanceName endget end property end class
4
2656
by: simon | last post by:
hello. relatively new to vb.net, i'm using VS 2003 and .net 2.0 i have a web app that i'm i have a user control that displays a simple 1 row table as the header of the page. the user control takes one input variable, the string that will be displayed as the title of the page. example call: <uc1:Header runat=server ID="ucHeader" Title="Home Page" /> what i am looking to do on a certain page is have the "title" value be dynamic, in...
12
3120
by: titan nyquist | last post by:
I have a class with data and methods that use it. Everything is contained perfectly THE PROBLEM: A separate thread has to call a method in the current instantiation of this class. There is only ever ONE instantiation of this class, and this outside method in a separate thread has to access it. How do i do this?
19
1953
by: =?Utf-8?B?WWFua2VlIEltcGVyaWFsaXN0IERvZw==?= | last post by:
I'm doing my c# more and more like i used to code c++, meaning i'm casting more often than creating an instance of objects. like : protected void gvOrderDetailsRowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { switch (((Sale)e.Row.DataItem).SzPN) {
45
3019
by: =?Utf-8?B?QmV0aA==?= | last post by:
Hello. I'm trying to find another way to share an instance of an object with other classes. I started by passing the instance to the other class's constructor, like this: Friend Class clsData Private m_objSQLClient As clsSQLClient Private m_objUsers As clsUsers
0
9621
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
9454
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
10106
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
10039
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,...
0
9914
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...
0
6716
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
5355
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
5484
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4009
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

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.