I have this code:
variable = "FFFF"
message = bytearray( variable.decode("hex") )
after this, I want to perform something like this:
message.len()
but it seems that bytearray does not have something like "len()" implemented, is it possible to know the lenght?
The idiom used for this in python is len(obj)
, not obj.len()
>>> v = 'ffff'
>>> msg = bytearray(v.decode('hex'))
>>> len(msg)
2
If you are creating your own class that should be able to report its length, implement the magic method __len__(self)
, which will be called when the built-in function len()
is called and passed an instance of your class.
See this old post from Guido:
(a) For some operations, prefix notation just reads better than postfix — prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x*(a+b) into xa + xb to the clumsiness of doing the same thing using a raw OO notation.
(b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len().
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