[python] AttributeError: 'tuple' object has no attribute

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'

This question is related to python python-2.7

The answer is


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


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.


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

I am working in python flask: I had the same problem... There was a "," after I declared my my form variables; I am working with wtforms. That is what caused all the confusion