473,768 Members | 3,968 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Setting "value" of an int-derived class

Lets say I want an integer class that lets you attach arbitrary
attributes. I can simply do:

class foo(int): pass

x = foo(5)
x.text = "okay"
print x, x.text # prints "5 okay"

So, that's good. But, how can I change the value of x from 5 to
something else, without creating a new instance?

I suppose I could create a function that creates a new "foo" and copies
its attributes, but is there a more direct way? Is the value "5" stored
in some special attribute I can just directly modify?

thanks,
Ken
Sep 2 '06 #1
2 1883
Ken Schutte schrieb:
Lets say I want an integer class that lets you attach arbitrary
attributes. I can simply do:

class foo(int): pass

x = foo(5)
x.text = "okay"
print x, x.text # prints "5 okay"

So, that's good. But, how can I change the value of x from 5 to
something else, without creating a new instance?

I suppose I could create a function that creates a new "foo" and copies
its attributes, but is there a more direct way? Is the value "5" stored
in some special attribute I can just directly modify?
You can't do that - the base class is immutable. Subclassing doesn't
change that.

What you can do of course in to create a class foo that will store its
value in an attribute, and overload the arithmetic operators and methods
like __int__, __long__ and __float__.

Diez
Sep 2 '06 #2
Ken Schutte wrote:
So, that's good. But, how can I change the value of x from 5 to
something else, without creating a new instance?

I suppose I could create a function that creates a new "foo" and copies
its attributes, but is there a more direct way? Is the value "5" stored
in some special attribute I can just directly modify?
In short, no. In long, ints (and longs, for that matter) are immutable
types implemented in a way that Python can't peek at their internals
easily, and so are very resistant to mutability. Imagine the results if
you mutated 5 to 6 or similar; in fact, you don't want regular numbers
to change without some serious hackage.

As for subclasses, a similar thing holds: Python programs can't see the
internal details. Subclasses just forward the method calls like
__add__, __xor__ etc (providing they're not overriden) to the int
class, which in turn pokes around at the C level and returns an answer.

What you probably want is a proxy class, that forwards all number
methods to a wrapped int, and also has a means of setting the wrapped
int. A minimal untested implementation:

class IntWrapper(obje ct):
def __init__(self, num):
self.num = num
def __getattr__(sel f, attr):
if attr == 'num':
return object.__getatt r__(self, 'num')
return getattr(self.nu m, attr)

Of course, this isn't actually what you asked for, a subclass of int.
But, bar hacking on the C level, which is possible but a bit extreme,
this is the closest thing to a mutable number.

But, personally, I happen to like the memory-wastetastic,
new-instance-returning but functionally purer style. It tends to lead
to less irreplicable bizarre bugs because of objects seemingley
semi-randomly changing state, and Python's garbage collection systems
are fairly good at picking up unused objects. ;)

--Sam

Sep 2 '06 #3

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

Similar topics

1
3237
by: Denzil | last post by:
Hi, I am retrieving my DB values and setting them in the MyRS::DoFieldExchange(CFieldExchange* pFX) function. One of these records is a Long datatype and could be "Null" in the DB table. The issue is when the DB value is retrieved it is fine for all integers but for a "Null" value it returns a junk long value and not a pre-defined value, say.
388
21896
by: maniac | last post by:
Hey guys, I'm new here, just a simple question. I'm learning to Program in C, and I was recommended a book called, "Mastering C Pointers", just asking if any of you have read it, and if it's worth the $25USD. I'm just looking for a book on Pointers, because from what I've read it's one of the toughest topics to understand. thanks in advanced.
14
2106
by: TTroy | last post by:
Hello, can anyone explain why the following function will not work for INT_MIN: /* itoa: convert n to characters in s */ void itoa(int n, char s) { int i, sign; if((sign = n) < 0) /* record sign */
5
6759
by: n_o_s_p_a__m | last post by:
Can't compile. Does this mean that all functions that throw exceptions must be of return type void? examples: // won't compile: "not all code paths return a value" public override int Run() { throw new Exception("exception thrown"); }
11
2655
by: ajikoe | last post by:
Hello, I used Visual C# Standard Edition. I want to comment my program using xml commentary method, I don't know why if I use value and example tag, it is not working / showed in the html result. for example I have Property ///<value>this is in description</value> ///<example>this is in Example</example> public int A{
2
3797
by: gabon | last post by:
I'm creating a select entirely through JavaScript and very strangely IE doesn't show the text in the option elements. Here part of the code: this.form_country=document.createElement("select"); var option; for(var i=0; i<arr.length; i++){ option=document.createElement("option"); option.value=arr.code;
10
2195
by: mdh | last post by:
Quick question about pointers. Wrote this "trying to understand this better" code: int *ptr, x = 565; ptr= &x; printf("\n\n\nThe value of x is %d\n", x);
21
2418
by: Steven T. Hatton | last post by:
I'm trying to improve my formal understanding of C++. One significant part of that effort involves clarifying my understanding of the vocabulary used to describe the language. This is from the C++ Standard: "" "...sequence of operators and operands that specifies a computation...". That means to me that an expression can be "executed". I am purposely
5
2275
by: Diwa | last post by:
Does the "value" type (value as in key-value pair )of "std::map" require a default ctor even if it is not used ? If I comment out Line 1 in the code attached later, i.e remove the default ctor of "value" type of map, I get the following error: // -------------------------------------------- /usr/include/c++/3.2.3/bits/stl_map.h:225: no matching function for call to `FieldType::FieldType()'
10
1742
by: hall.jeff | last post by:
As a relative new comer to Python, I haven't done a heck of a lot of hacking around with it. I had my first run in with Python's quirky (to me at least) tendency to assign by reference rather than by value (I'm coming from a VBA world so that's the terminology I'm using). I was surprised that these two cases behave so differently test = ,] x = test x = 5 test
0
9412
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
10022
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
9969
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
9847
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
8843
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6659
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
5289
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...
2
3543
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2810
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.