Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.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中向现有类/对象添加函数_Python - Fatal编程技术网

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

如何在Python中向现有类/对象添加函数,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') 如果可能的话,请告诉我。请指导我如何实现这一点。我

我正在使用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", "")
''

我认为你应该使用
get

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

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'

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'

很好的解释是的。。这有帮助。有没有什么风格的get也可以得到嵌套的属性。像record['address']['postal_code']?@NeerajKumar是的,你可以做
record.get('address',{}).get('postal_code')
@David542谢谢你帮我。只是出于好奇,Python能够提供定义函数并将其附加到现有类或对象的功能。请参考我问题中的代码。解释得很好是的。。这有帮助。有没有什么风格的get也可以得到嵌套的属性。像record['address']['postal_code']?@NeerajKumar是的,你可以做
record.get('address',{}).get('postal_code')
@David542谢谢你帮我。只是出于好奇,Python能够提供定义函数并将其附加到现有类或对象的功能。请参考我问题中的代码。您可以编写一个可以从JSON数据构造的类。否则,python会将其反序列化为一个
dict
,该dict将用作映射,而不是一个具有方法的对象。您可以编写一个可以从JSON数据构造的类。否则,python将其反序列化为
dict
,该dict将用作映射,而不是带有方法的对象