首页 > 解决方案 > 如何将函数添加到 Python 中的现有类/对象

问题描述

我正在使用 Python 读取 JSON 对象。下面是示例。

var name = jsonObj['f_name'];

我想定义一个可以直接从 jsonObj 调用的函数。下面是伪代码。

def get_attribute(key):
  if key in this
    return this[key]
  else
    return ''

然后我想使用这个功能,如下所示。

jsonObj.get_attribute('f_name')

让我知道这是否可能。请指导我实现这一目标。

标签: python

解决方案


我认为你应该使用get

>>> dictionary = {"message": "Hello, World!"}
>>> dictionary.get("message", "")
'Hello, World!'
>>> dictionary.get("test", "")
''

推荐阅读