IPv4Address.compressed ipaddress 的含义

IPv4Address.compressed meaning for ipaddress

当我阅读 ipaddress 文档时:

https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Address.compressed

当我阅读 IPv4Address.compressed 时,我发现 compressed 没有解释。

谁能告诉我这是什么意思?


来自来源 代码,这里只有Return the shorthand version of the IP address as a string.解释,我不是很懂shorthand version of the IP address

I find there is no explain for the compressed

实际上documented一起爆炸 属性:

compressed

exploded

The string representation in dotted decimal notation. Leading zeroes are never included in the representation.

As IPv4 does not define a shorthand notation for addresses with octets set to zero, these two attributes are always the same as str(addr) for IPv4 addresses. Exposing these attributes makes it easier to write display code that can handle both IPv4 and IPv6 addresses.

对于 IPv4 和 IPv6 地址,属性 本身在基础 class 中是 defined,如下所示:

@property
def compressed(self):
    """Return the shorthand version of the IP address as a string."""
    return str(self)

对于 IPv4Address 对象 str(self) 将 return 一个 string 以小数点表示法,例如"192.168.0.1".

compressedexploded 是由基 class ipaddress._IPAddressBase 定义的属性,因此每个 ip 地址实例都有它们。对于 IPv4,两者之间没有区别,因为历史上不需要更短的表示形式:

>>> i4 = ipaddress.IPv4Address("127.0.0.1")
>>> i4.exploded
'127.0.0.1'
>>> i4.compressed
'127.0.0.1'

不同之处在于 ipv6 地址:

>>> i6 = ipaddress.IPv6Address("::1")
>>> i6.exploded
'0000:0000:0000:0000:0000:0000:0000:0001'
>>> i6.compressed
'::1'

此处省略 0 组对可用性有很大帮助。

由于所有地址都具有这两个属性,因此您无需关心地址对象的类型。如果只有 IPv6Address 个对象有一个 exploded 属性,那么在处理混合地址类型时使用它会更麻烦。