我是 python 的初学者。我不明白问题出在哪里?
def list_benefits():
s1 = "More organized code"
s2 = "More readable code"
s3 = "Easier code reuse"
s4 = "Allowing programmers to share and connect code together"
return s1,s2,s3,s4
def build_sentence():
obj=list_benefits()
print obj.s1 + " is a benefit of functions!"
print obj.s2 + " is a benefit of functions!"
print obj.s3 + " is a benefit of functions!"
print build_sentence()
我得到的错误是:
Traceback (most recent call last):
Line 15, in <module>
print build_sentence()
Line 11, in build_sentence
print obj.s1 + " is a benefit of functions!"
AttributeError: 'tuple' object has no attribute 's1'
原文由 Alok 发布,翻译遵循 CC BY-SA 4.0 许可协议
您返回四个变量 s1、s2、s3、s4 并使用单个变量
obj
接收它们。这就是所谓的tuple
,obj
与 4 个值相关联,即s1,s2,s3,s4
的值。因此,像在列表中使用的那样使用索引来按顺序获取所需的值。