473,388 Members | 1,277 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,388 software developers and data experts.

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 1864
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(object):
def __init__(self, num):
self.num = num
def __getattr__(self, attr):
if attr == 'num':
return object.__getattr__(self, 'num')
return getattr(self.num, 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
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...
388
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...
14
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) /*...
5
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() {...
11
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...
2
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");...
10
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
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...
5
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...
10
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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...
0
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...

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.