I have a custom class in python which I need to pass to an external API. The API only requires to be able to invoke bytes(...)
on my class.
My question is, how can I decide the behavior of invoking bytes()
on my custom python class?
Python bytes() FunctionIt can convert objects into bytes objects, or create empty bytes object of the specified size. The difference between bytes() and bytearray() is that bytes() returns an object that cannot be modified, and bytearray() returns an object that can be modified.
The first is you use a function bytes() , and enclosed in arguments you put in a string followed by the type of encoding. 00:17 This will create a bytes object from that string. The second way is by using the bytes() function and entering in a size.
The bytearray type is a mutable sequence of integers in the range between 0 and 255. It allows you to work directly with binary data. It can be used to work with low-level data such as that inside of images or arriving directly from the network. Bytearray type inherits methods from both list and str types.
You can give your custom class a __bytes__
method:
Called by
bytes
to compute a byte-string representation of an object. This should return abytes
object.
Demo:
>>> class Foo:
... def __bytes__(self):
... return b'This is a bytes result for this instance'
...
>>> bytes(Foo())
b'This is a bytes result for this instance'
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