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")
AttributeError: 'simple' object has no attribute 'show'
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.