Reputation: 2606
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
Upvotes: 0
Views: 108
Reputation: 4483
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
Upvotes: 3
Reputation: 28987
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
.
Upvotes: 4
Reputation: 43
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.
Upvotes: 1
Reputation: 10057
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
.
Upvotes: 2