AttributeError: 'tuple' object has no attribute

匿名 (未验证) 提交于 2019-12-03 08:33:39

问题:

I'm a beginner in python. I'm not able to understand what the problem is?

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() 

The error I'm getting is:

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' 

回答1:

You return four variables s1,s2,s3,s4 and reveive them using a single variable obj. This is what is called a tuple, obj is associated with 4 values, the values of s1,s2,s3,s4. So, use index as you use in a list to get the value you want, in order.

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!" 


回答2:

You're returning a tuple. Index it.

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!" 


回答3:

Variables names are only locally meaningful.

Once you hit

return s1,s2,s3,s4

at the end of the method, Python constructs a tuple with the values of s1, s2, s3 and s4 as its four members at index 0, 1, 2 and 3 - NOT a dictionary of variable names to values, NOT an object with variable names and their values, etc.

If you want the variable names to be meaningful after you hit return in the method, you must create an object or dictionary.



回答4:

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() 

I know it is late answer, maybe some other folk can benefit If you still want to call by "attributes", you could use class with default constructor, and create an instance of the class as mentioned in other answers



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!