-3

I have a class "NN" which trains a neural network. The problem is that some of the methods in the class can not be seen/used by the others, line 47 and 50 says "undefined name truncated_normal". I can create an "NN"-class, but when I try call say nn.create_weights() it throws an error, that "truncated_normal" does not exists. The same goes for af(x) and daf(x)

enter image description here

Any suggestions?

CutePoison
  • 4,679
  • 5
  • 28
  • 63

1 Answers1

1

If you are referencing a method of the same class, you need to preface it with self.

For example, line 47 would read:

self.wmatlayer = self.truncated_normal(....

Don't forget that when calling a method, you are calling something which belongs to the class instance, so you need to include the self before it just like how you include self when referencing an attribute like self.wmatlayer.

Keshinko
  • 318
  • 1
  • 11
  • You should also mention that the other methods either need `self` as the first argument, or to be decorated as `staticmethod` – SpoonMeiser Aug 29 '18 at 14:32
  • Thank you so much! It worked :D – CutePoison Aug 29 '18 at 14:33
  • @SpoonMeiser Also if you don't need to use any "self" variable? The function ` af(x) ` does not need some of the class variables, it just calculates max(0,x) – CutePoison Aug 29 '18 at 14:35
  • @Jakob Then move it out of the class. – Aran-Fey Aug 29 '18 at 14:35
  • @Aran-Fey Some of the methods in the class does need it, but the function just takes one input and calculate the maximum of that or 0, thus it only need access to its input. – CutePoison Aug 29 '18 at 14:37
  • @Jakob Then keep those methods in the class. – Aran-Fey Aug 29 '18 at 14:38
  • @Jakob You need to tell the interpreter _where_ the function is. Sometimes you do this implicitly, by not specifying a location. In that case, it looks at the methods defined at the highest level of the file (no indent). However, methods within classes are not at this highest level. So, you need to tell it to look at `self`, that is, within the class it is currently in. If some other method needs to use `af()`, then `af()` doesn't need to be in the class. You can keep `af()` wherever you want, just make sure to specify its location with `self` or by not putting any prefix. – Keshinko Aug 29 '18 at 14:49