gpt4 book ai didi

python - 有没有办法知道python中bytearray变量的长度?

转载 作者:行者123 更新时间:2023-12-02 06:57:05 25 4
gpt4 key购买 nike

我有这个代码:

variable = "FFFF"
message = bytearray( variable.decode("hex") )

在此之后,我想执行以下操作:
message.len()

但似乎bytearray没有实现“len()”之类的东西,是否有可能知道长度?

最佳答案

在 python 中用于此的习语是 len(obj) ,不是 obj.len()

>>> v = 'ffff'
>>> msg = bytearray(v.decode('hex'))
>>> len(msg)
2

如果您正在创建自己的类并且应该能够报告其长度,请实现魔术方法 __len__(self) , 内置函数 len() 时会调用被调用并传递了你的类的一个实例。

为什么?

this old post来自圭多:

(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().

关于python - 有没有办法知道python中bytearray变量的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29304342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com