-3

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 lambda 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=' , ')
2
  • 4
    Thats really not what lambdas are made for... You should use a normal function. Commented Jul 22, 2023 at 13:16
  • 1
    side note, use **2 to square. Commented Jul 22, 2023 at 13:26

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

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.