在Python中的类中使用函数(是否使用self)

a1l*_*ord 6 python class function self

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
Run Code Online (Sandbox Code Playgroud)

我不知道为什么它不会用 sigmoid 函数打印 a1 变量。它不断地启动一个错误,说它需要 2 个输入而不是 1 个。但我认为通过调用类中的函数,我不需要再次向它提供 self ?

编辑:我在那里有最后两条语句,因为我仍在测试一些东西,以确保一切都在类中按照预期进行。

Rob*_*cia 1

sigmoid是类的方法,因此如果您在类定义之后调用它,则需要先Neuralnetwork创建该类的实例,然后才能使用该函数:Neuralnetworksigmoid

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
Run Code Online (Sandbox Code Playgroud)

如果您需要在类中使用它,请将块放在方法中:

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)
Run Code Online (Sandbox Code Playgroud)

我还建议将类名更改为NeuralNetwork,按照 PEP 8 风格指南:https://www.python.org/dev/peps/pep-0008/#class-names