Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python bytes(...) on custom class

Tags:

python

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?

like image 219
Elad Weiss Avatar asked Jun 12 '17 13:06

Elad Weiss


People also ask

What is Python class bytes?

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.

How do you declare a byte object in Python?

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.

What is Bytearray data type in Python?

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.


1 Answers

You can give your custom class a __bytes__ method:

Called by bytes to compute a byte-string representation of an object. This should return a bytes 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'
like image 150
Martijn Pieters Avatar answered Sep 27 '22 20:09

Martijn Pieters