a1letterword
a1letterword

Reputation: 307

Using a function within a class in python (to use self 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 with the sigmoid function. It keeps kicking off an error saying that it requires 2 inputs instead of 1. But I thought that by calling the function within the class, I didn'tneed to supply self to it again?

Edit: I have the last two statements in there because I'm still testing things out to make sure that everything is doing what it's supposed to within the class.

Upvotes: 6

Views: 7972

Answers (3)

progmatico
progmatico

Reputation: 4964

I notice that your sigmoid method does not use self at all, that is, it does not depend on the instance. You may put it outside the class as a normal function. But if it is closely related to the class, you may prefer to enclose it as a static method, removing completely the self from the sigmoid def:

#/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))

Upvotes: 4

Robert Valencia
Robert Valencia

Reputation: 1752

sigmoid is a method of the Neuralnetwork class, so you need to create an instance of the Neuralnetwork class first, before you can utilize the sigmoid function, if you're calling 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 within the class, put the block within 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 to NeuralNetwork, as per the PEP 8 Style Guide: https://www.python.org/dev/peps/pep-0008/#class-names

Upvotes: 1

Astrom
Astrom

Reputation: 767

with the two last line outside your class (without indentation) you can modify them with:

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

but you have to give data to your class

Upvotes: 0

Related Questions