python - 如何将函数添加到 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')
让我知道这是否可能。请指导我实现这一目标。
解决方案
我认为你应该使用get
>>> dictionary = {"message": "Hello, World!"}
>>> dictionary.get("message", "")
'Hello, World!'
>>> dictionary.get("test", "")
''
推荐阅读
- python - 如何用python调用特定的shell?
- reactjs - Firestore在React Application中通过Redux-Saga添加数据时添加重复记录
- r - 为什么 which(c(TRUE, FALSE, TRUE)) 在这个 R 漩涡教程中返回向量 c(1, 3)?
- ruby-on-rails - 如何将格式化的字符串转换为纯文本
- javascript - 将 Leaflet-lasso JS 插件与 Leaflet for R 一起使用
- javascript - React new Set 方法如何访问值?
- c# - 如何将数据方案转换为图像并保存
- json - 在 DTO 对象上映射嵌套 JSON 对象的有效方法
- azure-devops - 是否可以将模板用作 Azure DevOps 管道装饰器的后端?
- wordpress - Wordpress WP_Query,从元术语中排除日期