Home > Software design >  What is the equivalent of a javascript callable function as a class parameter in python?
What is the equivalent of a javascript callable function as a class parameter in python?

Time:10-08

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')

CodePudding user response:

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()

CodePudding user response:

You can use a lambda for simple functions.

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

myFunc = myClass()
myFunc.hi()

CodePudding user response:

It's pretty simple in python,

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

c = MyClass()
c.func()
  • Related