0
import numpy as np

class Y:
    def __init__(self):
        return None

    def f(self,x):
        return x

    def g(self,x):
        return f(x)**2
y=Y()
print y.g(3)

I know the above code will give error, but somehow I want to do the following, is there a modification to do?

5
  • 1
    Change "return f(x)**2" to "return self.f(x)**2" Commented Jun 19, 2015 at 23:41
  • 3
    __init__ shouldn't return anything. If you want it to do nothing, use pass. Commented Jun 19, 2015 at 23:46
  • Every function returns something. If the function has a lone return or simply ends with no return statement at all, it returns None by default. Adding a return None to the end of a method that traditionally has no return statement doesn't bother it. Commented Jun 19, 2015 at 23:54
  • 1
    If __init__() doesn't do anything, just leave it out. Commented Jun 20, 2015 at 3:33
  • g() should be return self.f(x)**2. Commented Jun 20, 2015 at 3:34

2 Answers 2

3

The only reason it doesn't work is because you have f(x)**2 instead of self.f(x)**2. Make that change and it'll work perfectly.

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

Comments

1

Yup. It just takes a simple change. Since f(x) is a method, you need to call it on some object. What you want here is to call it on yourself, so very simply that line becomes:

return self.f(x)**2

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.