我编写了一个如下函数,带有可选参数'b'。
url取决于b的存在。
def something(a, b=None)
if len(b) >= 1:
url = 'http://www.xyz.com/%sand%s' % (a, b)
else:
url = 'http://www.xyz.com/%s' (a)
b=None当说“'none-type'类型的对象没有长度”时,这会引发错误
任何想法如何解决这个问题?
您可以简单地使用if b:- 这将要求该值None既不是空字符串/列表/其他值也不是空字符串。
你可以简单地改变 -
def something(a, b=None)
到 -
def something(a, b="")
除非你真的需要检查 的长度,否则b为什么不简单地做
if b is not None:
...
如果您还需要检查长度(因此该else部分也执行 if b == ""),请使用
if b is not None and len(b) >= 1:
...
and运算符短路,这意味着 if ,b is None表达式的第二部分甚至没有被计算,所以不会引发异常。
要评估bwhen it's not的长度,请将语句None更改为:if
if b is not None and len(b) >= 1:
...
由于and运算符的原因,如果第一个测试 ( ) 失败,len(b)则不会进行评估。b is not None即表达式求值是短路的。
你可以试试这段代码:
def something(a, *b):
if len(b) == 0:
print('Equivalent to calling: something(a)')
else:
print('Both a and b variables are present')