-5

I want to give an int a function, e.g.:

>>> def x.converttostring(): 
...     return str(self)

>>> x = 1
>>> print x.converttostring()
'1'
>>> print x
1

ideally I want to have it operating on select ints, not all ints, e.g.

>>> x.converttostring()
'1'
>>> y.converttostring()
Traceback (most recent call last):
  ...
AttributeError: 'int' object has no attribute 'converttostring'

Is it possible? The function part is essential (not str(x)) and creating a class is out of the question.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Bitmap Image
  • 201
  • 3
  • 7
  • Did you know `int` is already a class and integers are functions with methods? There is a `int.__str__()` method, for example, that does *exactly what your method does*, return a string representation of the integer. – Martijn Pieters Sep 28 '15 at 14:02
  • 3
    Why on earth would you want to deliberately break OOP like that? If two objects are of the same class, they should have the same interface (methods, etc.) – jonrsharpe Sep 28 '15 at 14:03
  • Methods generally also always apply to *all* instances of a given class or type, not just some of them. Create a subclass if you want to have 'special' integers. That's incidentally also how you give built-in types additional methods; you subclass the type. – Martijn Pieters Sep 28 '15 at 14:03
  • martijn, how can i add my own methods to an int? – Bitmap Image Sep 28 '15 at 14:07
  • jonrsharpe, these ints are special purpose ints and used in special situations, but require the same flexibility as a standard int – Bitmap Image Sep 28 '15 at 14:09
  • @BitmapImage: so you create a subclass for those situations. – Martijn Pieters Sep 28 '15 at 14:11
  • 1
    What problem are you trying to solve? – Peter Wood Sep 28 '15 at 14:21
  • 1
    **What** *"special situations"*?! Without much more explanation of why you don't want to do any of the sensible things, you're unlikely to get any helpful answers. Does *"creating a class"* include sub-classing? – jonrsharpe Sep 28 '15 at 14:28
  • Also read this for more explanation on why build in objects do not behave exactly as [normal classes](http://stackoverflow.com/questions/1529002/cant-set-attributes-of-object-class) – RickyA Sep 28 '15 at 14:50

3 Answers3

4

In Python, int is a class.

This:

Ideally I want to have it operating on select ints, not all ints.

Can easily be achieved using subclassing

For example, you can create a SpecialInt class:

class SpecialInt(int):

    def some_strange_method(self):
        return self + 1

This class will behave exactly like an int, but with additional behavior.

After that, you can instantiate your class this way:

special_int = SpecialInt(4)
print special_int.some_strange_method()
>>> 5

You can override anything you need from the base class, as well.

Keep in mind that any operation with SpecialInt will result in an int instance unless you override the operation methods, such as __add__. See the full numeric types specification in the documentation and the guidance on emulating numeric types.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Alvaro
  • 11,797
  • 9
  • 40
  • 57
  • However, note that most operations on this `SpecialInt` will result in an `int`, e.g. `1 + SpecialInt(2)` would be `3`, a regular `int`. – jonrsharpe Sep 28 '15 at 14:28
  • @jonrsharpe you're right, edited with the docs info about operations you should override to avoid that behavior – Alvaro Sep 28 '15 at 14:55
  • I don't think this will work, at least not how I'd like to implement it, I wanna define a class, have some ints defined as per normal, but those or some of those ints having custom methods. Defining each int as anything other then an int, is going to be too much work. My basic plan was just to asign a function defined else where to an int, hey fkin presto a magic int. Is that possible even if its a hack and van rossum will curse me for all eternity ? – Bitmap Image Sep 28 '15 at 15:18
  • @BitmapImage you can patch the built-in classes with [`forbiddenfruit`](https://github.com/clarete/forbiddenfruit), but not just a single instance. Again, please explain **why you think that you want to do this**. This seems a lot like an [XY problem](http://meta.stackexchange.com/q/66377/248731). – jonrsharpe Sep 28 '15 at 15:19
  • Im back home now, if you do a dir on a, and a=3 you see a function called bit_length () calling a.bit_length() returns 2, I want to give a a custom function that works just like bit_length(), except obviously I don't need a bit_length function – Bitmap Image Sep 28 '15 at 15:27
  • @BitmapImage *"I want to give a a custom function that works just like bit_length(), except obviously I don't need a bit_length function"* - *"like bit_length but not bit_length"*?! What you're describing is **any method**, and explains **precisely nothing**. Please [edit the question](http://stackoverflow.com/posts/32824888/edit) to give us some information about what you're **actually trying to achieve**. – jonrsharpe Sep 28 '15 at 15:30
  • 1
    Jonrsharpe, I'm writing a custom enumerator class, each value is stored as an int, but I want to add a tostring method to each int that converts the value into a string that is the name of the int so I can just drop enumerator values straight into an error message – Bitmap Image Sep 28 '15 at 15:33
  • 2
    @BitmapImage 1. You need to use `@` to notify users you're commenting (apart from the poor post owner, who's getting spammed - sorry, Alvaro). 2. There are many existing enumerator implementations (including [the canonical one](https://pypi.python.org/pypi/enum34/)) that already provide the appropriate behaviour, why are you trying to roll your own in such a weird way? 3. Put this information **in the question**. – jonrsharpe Sep 28 '15 at 15:35
0

I don't see any scenario where this is a correct solution, but you may try creating a subclass:

class MyInt(int):
    def custom_method(self):
        return "Int: " + str(self)

i = MyInt(3)
assert i == 3
assert i+2 == 5
assert i.custom_method() == "Int: 3"
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
-1

Apparently you can't add objects to ints, there is no dict and that seems to be an essential requirement. The problem with subclasses is in trying to define the following

A,b,c=range(0,3)

With int's it is really clean syntax, with subclasses it gets relatively messy. Thanks for the assistance :-)

I'm gonna try and bend a dictionary to my will instead!

Bitmap Image
  • 201
  • 3
  • 7