I need to make a variable with similar behaviour like in C lanquage. I need byte or unsigned char with range 0-255. This variable should overflow, that means...
myVar = 255
myVar += 1
print myVar #!!myVar = 0!!
In Python, OverflowError occurs when any operations like arithmetic operations or any other variable storing any value above its limit then there occurs an overflow of values that will exceed it's specified or already defined limit. In general, in all programming languages, this overflow error means the same.
When an integer value is passed to the bytes() method, it creates an array of that size (size = integer value) and initializes the elements with null bytes. In the following example, we are passing the value 6 to the bytes() method so the function created an array of size 6 and initialized the elements with null bytes.
Python bytes() Function The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size.
The primary difference is that a bytes object is immutable, meaning that once created, you cannot modify its elements. By contrast, a bytearray object allows you to modify its elements. Both bytes and bytearay provide functions to encode and decode strings.
I see lots of good answers here. However, if you want to create your own type as you mentioned, you could look at the Python Data model documentation. It explains how to make classes that have customized behaviours, for example emulating numeric types.
With this info, you could make a class like so:
class Num:
def __init__(self, n):
self.n = (n % 256)
def __repr__(self):
return repr(self.n)
def __add__(self, other):
return Num(self.n+int(other))
# transform ourselves into an int, so
# int-expecting methods can use us
def __int__(self):
return self.n
Then you can do things like this:
>>> a = Num(100)
>>> print a
100
>>> b = a + 50
>>> print b
150
>>> c = Num(200)
>>> d = a + c
>>> print d
44
I realize that you may want to support more operations than I've shown in Num
, but from this example and the documentation, it should be fairly clear how to add them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With