Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法从getter方法获取值_Python_Python 3.x - Fatal编程技术网

Python 无法从getter方法获取值

Python 无法从getter方法获取值,python,python-3.x,Python,Python 3.x,我刚开始学习Python。由于一些性能问题,我不得不在我的一个AWS Lambda函数中将所有代码从Java切换到Python。我正在使用lambda控制台提供的IDE 目前,我对Python中的类有点着迷。我读了很多教程,我认为我在setters和getter方法上所做的是正确的。这是我的密码: class User: def __init__(self, user): self.username = user def get_username(self):

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

目前,我对Python中的类有点着迷。我读了很多教程,我认为我在setters和getter方法上所做的是正确的。这是我的密码:

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_处理程序被调用时,我希望输出是

name of user is thisisname
name of user is whatever
但是,当我打印user.get_username的值时。类型错误被抛出。以下是我得到的错误消息:

{   "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>>
用户的名称为
用户名称为
您没有调用getter方法。将其更改为:

print("name of user is " + user.get_username())
话虽如此,Python的惯用用法并不像Java那样有getter和setter。python的方法是使用
@property
装饰器。有关详细信息,请参阅。

的可能副本