Inheriting from int or long

Terry Reedy tjreedy at udel.edu
Tue Oct 2 11:28:13 EDT 2007


<snorble at hotmail.com> wrote in message 
news:1191329955.229829.259130 at 22g2000hsm.googlegroups.com...
|I started creating a simple "bits" class, intended to act like a array
| of bits. This was my initial idea, basically just overriding the
| string representation to display the bitmask (so far):

For this purpose, for the reason you discovered, simply writing a bit_rep 
function would likely be better ;-)

[discovery of need to override possibly all of long's special methods]

|| Is there any way around this without reimplementing all of the bitwise
| operators? It's not the biggest deal to reimplement the operators, but
| it kind of defeats the benefit of inheriting from an integer type.

Since the code needed is mostly boilerplate, I think the standard Python 
distribution could and should contain builtin type subclass template files, 
at least for int/long/float for the reasons you give below.

| If there isn't a way around this, then I am curious in what situations
| it would be beneficial to inherit from an int or long.

As I already said, if you only want to change __str__, consider a 
standalone function. If you want to change the behavior of any of the 
operations and still tie into the syntax, then the alternative, wrapping 
the builtin, may be worse.

class mysub(int):
    ...
    def __add__(self, other): return mysub(self,other)

versus

class mywrap():
    def __init__(self,dat):
        self._int = dat # should test type
    def __add__(self, other): return mywrap(self._int + other._int)

| This issue
| seems more related to numeric types, since they are so centered around
| operations that involve assignment, as opposed to, say, a List, which
| has some operators (ex. +=), but does not depend on them (ex. use
| append() instead).

Terry Jan Reedy






More information about the Python-list mailing list