Alo*_*lok 27 python python-2.7
我是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()
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
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'
Run Code Online (Sandbox Code Playgroud)
Asw*_*esh 25
返回四个变量s1,s2,s3,s4并使用单个变量接收它们obj.这就是所谓的a tuple,obj与4个值相关联,值为s1,s2,s3,s4.因此,在列表中使用索引按顺序获取所需的值.
obj=list_benefits()
print obj[0] + " is a benefit of functions!"
print obj[1] + " is a benefit of functions!"
print obj[2] + " is a benefit of functions!"
print obj[3] + " is a benefit of functions!"
Run Code Online (Sandbox Code Playgroud)
你回来了tuple.索引它.
obj=list_benefits()
print obj[0] + " is a benefit of functions!"
print obj[1] + " is a benefit of functions!"
print obj[2] + " is a benefit of functions!"
Run Code Online (Sandbox Code Playgroud)
变量名称仅在局部有意义。
一旦你打
return s1,s2,s3,s4
在该方法的末尾,Python 构造了一个元组,其中 s1、s2、s3 和 s4 的值作为它在索引 0、1、2 和 3 处的四个成员 - 不是变量名称到值的字典,不是具有变量的对象名称及其值等。
如果您希望在您点击return方法后变量名称有意义,您必须创建一个对象或字典。
class list_benefits(object):
def __init__(self):
self.s1 = "More organized code"
self.s2 = "More readable code"
self.s3 = "Easier code reuse"
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()
Run Code Online (Sandbox Code Playgroud)
我知道这是迟到的答案,也许其他一些人可以受益