-2

How to implement lambda function within a class? Here is my code doing exactly what I want it to do with a square function but I want to see if it's possible to replace the square function with a lambada function.

class Cal:
    def __init__(self, num):
        self.num=num

    #squares = lambda num: num * 2

    def squares(self):
        return self.num*2

for i in range(11):
    s1=Cal(i)
    print(s1.squares())
class Cal:
    def __init__(self, num):
        self.num=num
    #squares = lambda num: num * 2
    def squares(self):
        return self.num*2

for i in range(11):
    s1=Cal(i)
    print(s1.squares(), end=' , ')
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

2 Answers2

1

You can, this will work fine for you:

class Cal:

    def __init__(self, num):
       self.num = num

    squares = lambda self: self.num * 2

for i in range(11):
     s1 = Cal(i)
     print(s1.squares())

BUT you shouldn't do this as lambdas are not meant to be used in this way. You can check this answer wich show how lambdas are typically used.

Andrey
  • 340
  • 2
  • 11
0

You can do:

class Cal:
    def __init__(self, num):
        self.num=num
Cal.squares = lambda cal: cal.num * 2

for i in range(11):
    s1=Cal(i)
    print(s1.squares(), end=' , ')

but there is no point in doing this

politinsa
  • 3,480
  • 1
  • 11
  • 36