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.
Why?
See this old post from Guido:
(a) For some operations, prefix notation just reads better thanpostfix — prefix (and infix!) operations have a long tradition inmathematics which likes notations where the visuals help themathematician thinking about a problem. Compare the easy with which werewrite a formula like x*(a+b) into xa + xb to the clumsiness ofdoing the same thing using a raw OO notation.
(b) When I read code that says len(x) I know that it is asking for thelength of something. This tells me two things: the result is aninteger, 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 ofcontainer implementing an interface or inheriting from a class thathas a standard len().