What is the equivalent of a javascript callable function as a class parameter in python?

Question:

In javascript, I do can add a function parameter to my function class like so:

const MyFunc = function(){
  const myfunc = this
  myfunc.hi = () => {
    console.log('hi')
  }
}

const myFunc = new MyFunc()
myFunc.hi()

What is the equivalent in python?

class MyClass:
    def __init__(self, hi):
        self.hi = def func():
            print('hi')
Asked By: Dshiz

||

Answers:

It’s pretty simple in python,

class MyClass:
    def func(self):
        print('hi')

c = MyClass()
c.func()
Answered By: Rahul K P

You could use a lambda.

self.hi = lambda: print('hi')

But it makes more sense to define a method on the class instead.

class MyClass:
    def hi(self):
        print('hi')

MyClass().hi()
Answered By: Unmitigated

You can use a lambda for simple functions.

class myClass:
    def __init__(self):
        myfunc = self
        myfunc.hi = lambda: print('hi')

myFunc = myClass()
myFunc.hi()
Answered By: Barmar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.