我是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'
答案 0 :(得分:20)
返回四个变量s1,s2,s3,s4并使用单个变量obj
接收它们。这就是所谓的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!"
答案 1 :(得分:8)
您将返回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!"
答案 2 :(得分:4)
变量名称仅在本地有意义。
一旦你点击
return s1,s2,s3,s4
在方法结束时,Python构造一个元组,其值为s1,s2,s3和s4作为其在索引0,1,2和3处的四个成员 - 不是变量名称到值的字典,而不是具有变量名称及其值等的对象
如果您希望在方法中点击return
后变量名称有意义,则必须创建对象或字典。
答案 3 :(得分:3)
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()
我知道这是迟到的答案,也许其他一些人可以受益 如果您仍想通过&#34;属性&#34;进行调用,则可以使用带默认构造函数的类,并创建其他答案中提到的类的实例
答案 4 :(得分:1)
我在python烧瓶中工作:我遇到了同样的问题……在声明我的表单变量后出现了一个“,”;我正在使用wtforms。那就是造成所有混乱的原因