0

I am working in one Python program where I want to create one object like we do in JavaScript.

var obj = {"sum":function(a,b){return a+b;}}`

Can I do a similar thing in Python?

4
  • You can, the equivalent in Python would be a lambda expression in a dictionary: obj = {"sum": lambda a, b: a + b}. Commented Aug 24, 2018 at 11:55
  • obj = {"sum", lambda a,b : a+b} should do your task. Commented Aug 24, 2018 at 11:56
  • @DeepakSaini no; that's a set, not a dictionary. Commented Aug 24, 2018 at 12:03
  • @jonrsharpe ohh yeah typo. Commented Aug 24, 2018 at 12:04

1 Answer 1

0

There are (at least) two ways of doing this:

test_obj = {
  'a': 'a',
  'func': lambda: print('test')
}

test_obj['func']()

Or:

def test():
  print('test')

test_obj = {
  'a': 'a',
  'func': test
}

test_obj['func']()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.