Using a function inside a class in python (to use it yourself or not)

class Neuralnetwork(object):

     def __init__(self, data):    
         self.data = data

     def scan(self):
         print(self.data)

     def sigmoid(self, z):
         g = 1 / (1 + math.exp(-z))
         return (g)

     a1 = sigmoid(7)
     print a1

      

I'm not sure why it won't print the a1 variable using a sigmoid function. It keeps on voicing an error stating that it requires 2 inputs instead of 1. But I thought that by calling the function inside the class, I wasn't trying to re-enroll it?

Edit: I have two last statements because I am still checking things to make sure everything is doing what it should have in the class.

+3


source to share


3 answers


sigmoid

is a method of the class Neuralnetwork

, so you first need to instantiate the class Neuralnetwork

before you can use the function sigmoid

if you call it after the class definition:

class Neuralnetwork(object):
     def __init__(self, data):    
         self.data = data

     def scan(self):
         print(self.data)

     def sigmoid(self, z):
         g = 1 / (1 + math.exp(-z))
         return (g)

# replace data and z with appropriate values
nn = Neuralnetwork(data)
a1 = nn.sigmoid(z)
print a1

      

If you need to use it inside a class, put a block in a method:



class Neuralnetwork(object):
     def __init__(self, data):    
         self.data = data

     def scan(self):
         print(self.data)

     def sigmoid(self, z):
         g = 1 / (1 + math.exp(-z))
         return (g)

     def print_sigmoid(self, z):
         a1 = self.sigmoid(z)
         print a1

# replace data and z with appropriate values
nn = Neuralnetwork(data)
nn.print_sigmoid(z)

      

I also recommend changing the class name Neuralnetwork

to according to the PEP 8 Style Guide: https://www.python.org/dev/peps/pep-0008/#class-names

0


source


with the last two lines outside of your class (no indentation) you can change them with:

a1 = Neuralnetwork(data).sigmoid(7)
print(a1)

      



but you have to provide data to your class

0


source


I notice that your sigmoid method is not using itself, meaning it is instance independent. You can place it outside the class as a normal function. But if it's closely related to the class, you might prefer it as a static method by removing itself from the sigmoid def entirely:

#/usr/bin/env python3

import math

class NeuralNetwork(object):

    def __init__(self, data):    
        self.data = data

    def scan(self):
        print(self.data)

    @staticmethod
    def sigmoid(z):
        g = 1 / (1 + math.exp(-z))
        return (g)

a1 = NeuralNetwork('abc')
print(a1.sigmoid(7))

      

0


source







All Articles