stone stone - 2 months ago 9
Python Question

the object does not have the specified attribute error in python

I am new to python. The following is the code.

class simple:
def __init__(self, str):
print("inside the simple constructor")
self.s = str


# two methods:

def show(self):
print(self.s)

def showMsg(self, msg):
print(msg + ":", self.show())


if __name__ == "__main__":
# create an object:
x = simple("constructor argument")

x.show()
x.showMsg("A message")


After I run it, I got the

AttributeError: 'simple' object has no attribute 'show'


So, does anyone know what's going on here? 'show' is not an attribute, right? For my understanding, it should be a method. Does anyone understand what's going on here? Many thanks for your time and attention.

Answer

You need to indent the methods to tell the interpreter that they are part of that class. Otherwise, you're simply creating standalone functions.

class simple:
    def __init__(self, str):
        print("inside the simple constructor")
        self.s = str

    # two methods:
    # note how they are indented

    def show(self):
        print(self.s)

    def showMsg(self, msg):
        print(msg + ":", self.show())

if __name__ == "__main__":
    # create an object:
    x = simple("constructor argument")

    x.show()
    x.showMsg("A message")

Technically, if you wanted, you could make the unindented version work anyway by using show(x) instead of x.show(), but it'd be clearer to fix the indentation as above.

Comments