如何在Python中向现有的类/对象添加函数

问题描述 投票:0回答:2

我正在使用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
2个回答
1
投票

我认为您应该使用get

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

1
投票

Arun回答了这个问题,但作为备用,您也可以使用函数或其他值。例如:

import json    
jsonObj=json.loads('{"f_name": "peter"}')

jsonObj.get('f_name')
# u'peter'

jsonObj.get('x_name','default')
# 'default'

jsonObj.get('x_name',jsonObj.get('f_name')) # or could just place it after the 
                                            # `get` with an or
# u'peter'
© www.soinside.com 2019 - 2024. All rights reserved.