0

As functions in Python are objects so we can pass them into other functions. For example:

def hello(x) :
    return "Hello World"*x
def bye(x) :
    return "Bye World"*x
def analyze(func,x) :
    return func(x)

For analyze(bye, 3) OUTPUT is Bye WorldBye WorldBye World

For analyze(hello, 3) OUTPUT is Bye World WorldHello World

It makes sense but while doing the same in-class Objects it throws an error. For example:

class Greetings:
   def __init__(self):
      pass
   def hello(self, x) :
      return "Hello World"*x
   def bye(self, x) :
      return "Bye World"*x
   def analyze(self, func, x) :
      return self.func(x)

Driver Code:

obj = Greetings()
obj.analyze(hello, 3)

Throws TypeError: analyze() missing 1 required positional argument: 'x'

I even tried obj.analyze(obj, hello, 3)

Then it throws AttributeError: type object 'Greetings' has no attribute 'func' exception.

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
Utkarsh
  • 137
  • 9
  • `self.func` accesses the attribute literally named `func`, which doesn't exist. Also you're passing the previously-defined `func` function, not the name of the method you want to call (i.e. a string). The dupe tells you how to access the method by name, but you'll have to change what you're calling `obj.analyze` with too. – jonrsharpe Oct 14 '20 at 11:34
  • I get "Name error: 'hello' not defined". it should be `obj.hello` or `Greetings.hello`. (Or if the other functions are still in scope, you should get "'Greetings' object has no attribute 'func'".) – tobias_k Oct 14 '20 at 11:35
  • @tobias_k I assume the original function is still in scope – jonrsharpe Oct 14 '20 at 11:35
  • 1
    Actually, your errors sound more like you accidentally did `obj = Greetings` instead of `obj = Greetings()` – tobias_k Oct 14 '20 at 11:38

2 Answers2

0

Can you try this,

class Greetings:
   def __init__(self):
      pass

   def hello(self, x) :
      return "Hello World"*x

   def bye(self, x) :
      return "Bye World"*x

   def analyze(self, func, x) :
      return func(x)

obj = Greetings()
print(obj.analyze(obj.hello, 3))
Maran Sowthri
  • 829
  • 6
  • 14
0
class Greetings:
   def __init__(self):
      pass
   def hello(self, x) :
      return "Hello World"*x
   def bye(self, x) :
      return "Bye World"*x
   def analyze(self, func, x) :
      return func(x)

obj = Greetings()
obj.analyze(obj.hello, 3)
Sergey Shubin
  • 3,040
  • 4
  • 24
  • 36
Glenn
  • 1