jeff jeff - 5 months ago 22
Python Question

Returning a function in Python

I get the following error "TypeError: make_pretty() takes exactly 1 argument (2 given)" for the below code snippet. I'm learning python and any help would be helpful...

class test:
def make_pretty(func):
def inner():
print("I got decorated")
func()
return inner

def ordinary():
print("I am ordinary")

pretty1 = test()
pretty = pretty1.make_pretty(pretty1.ordinary)
print(pretty())


I also tried it with decorators, but still face the same error..

class SmartDivide:
def smart_divide(self,func):
def inner(a,b):
print("I am going to divide",a,"and",b)
if b == 0:
print("Whoops! cannot divide")
return

return func(a,b)
return inner

@smart_divide
def divide(self,a,b):
return a/b

dvd = SmartDivide()
print(dvd.divide(2,5))
dvd.divide(2,0)

Answer

You may need the self keyword

class test:
    def make_pretty(self, func):
        def inner():
            print("I got decorated")
            func()
        return inner

    def ordinary(self):
        print("I am ordinary")

pretty1 = test()
pretty = pretty1.make_pretty(pretty1.ordinary)
print(pretty())