Python:ipaddress AttributeError:'str'对象没有属性 [英] Python: ipaddress AttributeError: 'str' object has no attribute
本文介绍了Python:ipaddress AttributeError:'str'对象没有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
按照此处给出的建议,我正在使用ipaddress
模块执行类型检查:
Following the advice given here, I'm using the check the ipaddress
module to perform checks of type:
In [25]: IPv4Address(u'100.64.1.1') in IPv4Network(u'100.64.0.0/10')
Out[25]: True
在IPython中工作正常.但是当我将其转换为功能时:
Works fine in IPython. Yet when I turn it into a function:
import ipaddress
def isPrivateIp(ip):
ip4addressBlocks = [u'0.0.0.0/8', u'10.0.0.0/8', u'100.64.0.0/10', u'127.0.0.0/8', u'169.254.0.0/16', u'172.16.0.0/12', u'192.0.0.0/24', u'192.0.2.0/24', u'192.88.99.0/24',
u'192.168.0.0/16', u'198.18.0.0/15', u'198.51.100.0/24', u'203.0.113.0/24', u'224.0.0.0/4', u'240.0.0.0/4', u'255.255.255.255/32']
unicoded = unicode(ip)
if any(unicoded in ipaddress.IPv4Network(address) for address in ip4addressBlocks):
return True
else:
return False
print isPrivateIp(r'169.254.255.1')
我得到:
File "isPrivateIP.py", line 14, in <module>
print isPrivateIp(r'169.254.255.1')
File "isPrivateIP.py", line 9, in isPrivateIp
if any(unicoded in ipaddress.IPv4Network(address) for address in ip4addressBlocks):
File "isPrivateIP.py", line 9, in <genexpr>
if any(unicoded in ipaddress.IPv4Network(address) for address in ip4addressBlocks):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ipaddress.py", line 705, in __contains__
if self._version != other._version:
AttributeError: 'str' object has no attribute '_version'
为什么呢?
推荐答案
在使用IPv4Address
实例之前,您要检查Unicode字符串ip
是否在网络中.
You check if the unicode string ip
is in the network, whereas before you've used an IPv4Address
instance.
您的测试必须是
if any(IPv4Address(unicoded) in ipaddress.IPv4Network(address) for address \
in ip4addressBlocks):
这篇关于Python:ipaddress AttributeError:'str'对象没有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文