Neeraj Kumar
Neeraj Kumar

Reputation: 245

How to add a function to existing class/object in Python

I am reading a JSON object using Python. Below is the example.

var name = jsonObj['f_name'];

I want to define a function which can be directly called from jsonObj. Below is the pseudo code.

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

And then I want to use this function as shown below.

jsonObj.get_attribute('f_name')

Let me know if this is possible. Please guide me on achieving this.

Upvotes: 0

Views: 59

Answers (2)

David542
David542

Reputation: 110123

Arun answers this, but as a fallback you can also use a function or another value. For example:

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'

Upvotes: 1

Arun Augustine
Arun Augustine

Reputation: 1766

I think you should use get

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

Upvotes: 1

Related Questions