无法从吸气剂方法获得价值

时间:2019-09-19 01:59:23

标签: python python-3.x

我刚刚开始学习Python。由于某些性能问题,我必须在我的一个AWS Lambda函数中将所有代码从Java切换到Python。我正在使用lambda控制台提供的IDE。

当前,我对Python的类有些困惑。我阅读了许多教程,我认为我对setter和getters方法所做的工作是正确的。这是我的代码:

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"

当调用lambda_handler时,我期望输出为

name of user is thisisname
name of user is whatever

但是,当我打印user.get_username的值时。引发TypeError。以下是我得到的错误消息:

{   "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" ] }

当我用str(user.get_username)包装它时,将打印方法说明。

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

1 个答案:

答案 0 :(得分:1)

您不是调用 getter方法。更改为:

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

话虽如此,Python习惯上没有Java中的getter和setter。 Pythonic 的实现方法是使用@property装饰器。有关详细信息,请参见this answer