0

I'm trying to get a construct a class that calls a function from within the same class but I'm having trouble doing so.

I've had a look at:

Python function pointers within the same Class

But I've had no luck with the approach presented. I've created this simple example:

#### Libraries ####
# Third Party Libraries  
import numpy as np

#### Defines the activation functions ####
class sigmoid_class(object):
    def __init__(self, z):
        self.z = z

    def activation_fn(self):
        """The sigmoid function"""
        return 1.0/(1.0+np.exp(-self.z))

    def prime(self):
        """The derivative of the sigmoid function"""
        return activation_fn(self.z)*(1-activation_fn(self.z))

a = sigmoid_class(0)
print(a.prime())

when I test with print(a.activation_fn(0)) I get the desired output, but when I try `print(a.prime())

I get `NameError: name 'activation_fn' is not defined

I'm not sure how to fix this so that it functions properly

6
  • 3
    use self.activation_fn() activation_fn is a member function of the class, so you need to give it the class instance (which is self) in order to call it. Commented Jul 18, 2016 at 22:13
  • self.activation_fn(self.z)*(1-self.activation_fn(self.z)) Commented Jul 18, 2016 at 22:13
  • I'm wondering whether the argument shouldn't be self -- not self.z as activation_fn signature is just self Commented Jul 18, 2016 at 22:14
  • 3
    @Keozon: Actually that should be self.activation_fn(). activation_fn doesn't take the z value as argument - it looks it up from self Commented Jul 18, 2016 at 22:15
  • @MartinBonner RIght, that's what I get for not looking close enough. Edited. Commented Jul 18, 2016 at 22:16

4 Answers 4

4

It should actually be:

def prime(self):
    """The derivative of the sigmoid function"""
    return self.activation_fn()*(1-self.activation_fn())

Note that activation_fn does not need to be passed the z value as well - it looks that up from self.

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

Comments

3

So combining both points:

def prime(self):
    """The derivative of the sigmoid function"""
    return self.activation_fn()*(1-self.activation_fn())

activation_fn finds self.z for itself

Comments

2
def prime(self):
    """The derivative of the sigmoid function"""
    return self.activation_fn(self.z)*(1-self.activation_fn(self.z))

Or so. note the self.activation_fn instead of just activation_fn.

Comments

1

The comments are correct, you need reference self. because activation_fn is not defined in the scope of the method itself, and your method also doesn't take in any arguments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.