473,729 Members | 2,148 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

changing value of 'self' when subclassing int

I'd like to subclass int to support list access, treating the integer
as if it were a list of bits.
Assigning bits to particular indices involves changing the value of
the integer itself, but changing 'self' obviously just alters the
value of that local variable.
Is there some way for me to change the value of the BitSequence
object itself? I've also tried wrapping and delegating using
__getattr__, but I couldn't figure out how to handle in-place methods.

Thanks for your help,
David Coffin
class BitSequence(int ):
"""An integer emulating a sequence of bits, subclassing int."""
def __new__(cls, value, length=32):
inst = super(BitSequen ce,cls).__new__ (cls, value)
inst.length = length
return inst

def __setitem__(sel f, index, bit):
mask = 1 << self.length - index - 1
if bit == 1:
# XXX only changing local 'self'
self |= mask
elif bit == 0:
self &= ~mask

def __getitem__(sel f, i):
return (self >> (self.length - i -1)) & 1

def __repr__(self):
s = ''
for i in xrange(self.len gth):
s = str(self >> i & 1) + s
return s + " : " + str(self)
Feb 20 '06 #1
4 2782
David Coffin <dc*****@gmail. com> wrote:
I'd like to subclass int to support list access, treating the integer
as if it were a list of bits.
Fine, but:
Assigning bits to particular indices involves changing the value of
the integer itself, but changing 'self' obviously just alters the


....integers are immutable, like all other numbers in Python: there is NO
way to "change the value of the integer itself".

I originally proposed to have "mutable numbers" (at least optionally) in
gmpy, but the reaction was a broadside against the idea, to the point
that I never got around to it -- gmpy includes a lot of functionality
for bit-level manipulation, but still only with immutable bitlists
(mapped into gmpy.mpz instances).
Alex
Feb 20 '06 #2

David Coffin wrote:
I'd like to subclass int to support list access, treating the integer
as if it were a list of bits.
Assigning bits to particular indices involves changing the value of
the integer itself, but changing 'self' obviously just alters the
value of that local variable.
Is there some way for me to change the value of the BitSequence
object itself? I've also tried wrapping and delegating using
__getattr__, but I couldn't figure out how to handle in-place methods.

Probably your best bet is to have the assignment done as a method call
which returns the new value.

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml
Thanks for your help,
David Coffin


Feb 21 '06 #3
David Coffin <dc*****@gmail. com> wrote:
I'd like to subclass int to support list access, treating the integer
as if it were a list of bits.
Assigning bits to particular indices involves changing the value of
the integer itself, but changing 'self' obviously just alters the
value of that local variable.
Is there some way for me to change the value of the BitSequence
object itself? I've also tried wrapping and delegating using
__getattr__, but I couldn't figure out how to handle in-place
methods.


Here was my take on the problem when it came up for me. Note the
FIXMEs ;-) My first attempt was to subclass long which was a dismal
failure.

class bits:
"""
Space efficient bit storage. It returns something which acts
like an infinitely long array. The array is initialised to all 0s

FIXME need to implement lots more methods!
FIXME check for -ve indices etc!
FIXME can do boolean methods by arithmetic on longs
FIXME can't subclass long as long is immutable :-(
"""
def __init__(self, initial = None):
"Initialise with the initial state of the array or nothing for it to be set to all 0s"
self.i = 0L
if initial:
for i in initial:
self.i <<= 1
self.i |= i
def mask(self, n):
return 1L << n
def __getitem__(sel f, n):
return (self.i & self.mask(n)) != 0L
def __setitem__(sel f, n, v):
m = self.mask(n)
if v:
self.i |= m
elif self.i & m:
self.i ^= m
# FIXME implement len() and use it in __repr__ to output directly!
def __repr__(self):
# FIXME is there a way to convert a long to binary?
content = ""
if self.i:
L = []
i = self.i
while i:
L.append(int(i & 1L))
i >>= 1
L.reverse()
content = str(L)
return "%s(%s)" % (self.__class__ .__name__, content)

--
Nick Craig-Wood <ni**@craig-wood.com> -- http://www.craig-wood.com/nick
Feb 21 '06 #4
Thanks for all the help.
On 20 Feb 2006, at 17:34, Alex Martelli wrote:

...integers are immutable, like all other numbers in Python: there
is NO
way to "change the value of the integer itself".
So, on learning that I could subclass the number types, I didn't even
consider the fact that they're immutable. I feel slightly foolish.
And I'll look at gmpy straight away, it looks like it contains
functionality I'll find useful.
On 21 Feb 2006, at 10:58, Fuzzyman wrote:

Probably your best bet is to have the assignment done as a method call
which returns the new value.


I not sure that would be suitable in this case. I'm using genetic
algorithm code containing some methods that assume 'individuals' are
represented as bitstrings, and some that assume individuals are
represented as lists of integers. Ideally, I could have created a
class for the bitstring individuals that also supported list based
bit assignment (without too much overhead).

Best wishes,
David Coffin
Feb 21 '06 #5

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

Similar topics

7
5827
by: Fuzzyman | last post by:
I'm writing a function that will query the comp.lang.python newsgroup via google groups....... (I haven't got nntp access from work..) I'm using urllib (for the first time)..... and google don't seem very keen to let me search the group from within a program - the returned pages all tell me 'you're not allowed to do that' :-) I read in the urllib manual pages : class URLopener( ])
1
1494
by: robin | last post by:
hi, i'm a newbie, but please bear with me for a second. i have this function inside a while-loop, which i'd like to loop forever, but i'm not sure about how to change the parameters of my function once it is running. what is the best way to do that? do i have to use threading or is there some simpler way? here's some code to show the structure of the problem:
4
1838
by: andychambers2002 | last post by:
I'm working on a "TempFile" class that stores the data in memory until it gets larger than a specified threshold (as per PEP 42). Whilst trying to implement it, I've come across some strange behaviour. Can anyone explain this? The test case at the bottom starts a TempFile at size 50 and prints its type. It then increases the size to the threshold at which point "self" is changed to being a TemporaryFile. It seems that the next call...
6
1720
by: PipedreamerGrey | last post by:
I'm using the script below (originally from http://effbot.org, given to me here) to open all of the text files in a directory and its subdirectories and combine them into one Rich text file (index.rtf). Now I'm adapting the script to convert all the text files into individual html files. What I can't figure out is how to trigger a change in the background value for each folder change (not each file), so that text is color-coded by...
4
1565
by: Mikael Olofsson | last post by:
Hi! This is in Python 2.3.4 under WinXP. I have a situation where I think changing the behaviour of a namespace would be very nice. The goal is to be able to run a python file from another in a separate namespace in such a way that a NameError is not raised if a non-existing variable is used in the file. The file that I want to run is taken out of context, and some needed variables may be missing that are normally there when used in...
4
3304
by: Tugrul HELVACI | last post by:
Changing DisplayNames of my properties using PropertyGrid component, how ?? I'm using Delphi 2006 and I have a class defination like this: TPerson = class fPersonName : String; fPersonSurName : String; fPersonAge : Integer; published property PersonName : String read fPersonName write fPersonName;
9
1635
by: manstey | last post by:
Hi, My question probably reflects my misunderstanding of python objects, but I would still like to know the answer. The question is, is it possible for an instnace to have a value (say a string, or integer) that can interact with other datatypes and be passed as an argument? The following code of course gives an error:
7
1361
by: Jorgen Bodde | last post by:
Hi, I am trying to simplify my code, and want to automate the assigning of variables I get back from a set. I was thinking of putting the variables I want changed in a list: L = self._varA is a variable I want to change when I pass L to a function. I know doing this;
275
12329
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
0
8911
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
8760
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
9426
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...
1
9200
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
8140
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...
1
6719
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...
1
3238
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
2673
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2162
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.