0

I just started learning Python. Due to some performance issue I have to switch all codes from Java to Python in one of my AWS Lambda functions. I am using the IDE provided by the lambda console.

Currently, I am a little stuck on classes in Python. I read a number of tutorials and I think what I did on setters and getters method are correct. Here is my code:

class User:
    def __init__(self, user):
        self.username = user

    def get_username(self):
        return self.username

    def set_username(self, user):
        self.username = user

def lambda_handler(request, context):
    user = User("thisisaname")
    print("name of user is " + user.get_username)
    user.set_username("whatever")
    print("name of user is " + user.get_username)
    return "executed"

When lambda_handler gets called, I am expecting the output to be

name of user is thisisname
name of user is whatever

However, when I am printing the value of user.get_username. TypeError is thrown. The following error message is what I got:

{   "errorMessage": "can only concatenate str (not \"method\") to str",   "errorType": "TypeError",   "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 28, in lambda_handler\n    print(\"name of user is \" + user.get_username)\n" ] }

When I wrap it with a str(user.get_username), the method description is printed.

name of user is <bound method User.get_username of <lambda_function.User object at 0x7f4d6a4cc4d0>> 
name of user is <bound method User.get_username of <lambda_function.User object at 0x7f4d6a4cc4d0>>
tripleee
  • 175,061
  • 34
  • 275
  • 318
JLT
  • 3,052
  • 9
  • 39
  • 86
  • Possible duplicate of [Python Beginner - where comes > from?](https://stackoverflow.com/questions/28879886/python-beginner-where-comes-bound-method-of-object-at-0x0000000005ea) – tripleee Sep 19 '19 at 05:58

1 Answers1

1

You are not calling the getter method. Change it to:

print("name of user is " + user.get_username())

That being said, Python idiomatically doesn't have getters and setters as in Java. The Pythonic way to do it is to use the @property decorators. See this answer for details.

Selcuk
  • 57,004
  • 12
  • 102
  • 110