This question already has answers here:
How can I call a function within a class?
(2 answers)
Closed 4 years ago.
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)
Any suggestions?
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.
Related
This question already has answers here:
making a class callable in same instance
(2 answers)
Closed 1 year ago.
I would like to define in python a class that behaves like a function with additional attributes. In particular, it should be seamlessly applied to a variable.
Let’s try to explain with a mathematical example. Say I am very much into sinusoïdal functions, but also interested by their frequency. A function x -> sin(omega x) has the attribute frequency, namely the value of omega. It can also be applied to a float x.
I can write:
from numpy import sin, pi
class SinFunc:
def __init__(self, omega):
self.frequency = omega
def apply_to(self, x):
return sin(self.frequency * x)
I could then play with a sinusoïdal function:
MySinFunc = SinFunc(3)
print(MySinFunc.frequency)
print(MySinFunc.apply_to(pi))
# output
# 3
# 0 (almost!)
But what I would like is to be able to write directly MySinFunc(pi), with the attribute frequency still defined.
How to achieve that?
Thanks!
To make an object callable, you need to add a __call__ class method that will handle the call.
Rename your apply_to function to __call__ and it will work.
This question already has answers here:
How do I use a keyword as a variable name?
(3 answers)
Closed 2 years ago.
I have stumbled upon the following syntax error with my Python3 interpreter:
class Class:
pass
a = Class()
a.from = 2
a.from = 2
^
SyntaxError: invalid syntax
Assignment of attributes that do not contain .from seem to be working fine:
a = Class()
a.fro = 2
print(a.__dict__)
{'fro': 2}
I understand that the standalone from statement is reserved for imports but struggle to understand why that would matter in the context of a class with the same key in its dict. Can someone explain why the interpreter complains at this point?
Simply because it's a reserved keyword that you can't use as an identifier.
The same issue would arise with e. g. x.in, x.for, x.import,...
This question already has answers here:
How to access (get or set) object attribute given string corresponding to name of that attribute
(3 answers)
Closed 3 years ago.
I have a list of methods that i wish to apply on a list of objects. The objects contain info that will change the outcome of the methods. I will then store the objects that got an outcome that i want.
The code looks as the following: where chefs is the objects that should carry out an action on an ingredient.
I am getting this error AttributeError: 'Chef' object has no attribute 'possibleAction'
It seems like the compiler does not take the value from possibleAction (which i want) and instead just take the name of the variabel.
I am not sure if this is possible but i know that you can store function in variabels and then call them, so then this maybe works on methods too i thought. Anyway i am appriacting all the help i can get, cheers :)
possibleStates = []
for chef in state.getChefs():
for possibleAction in getAllPossibleActionForChef():
for ingredient in state.getKitchen().getIngredients():
newPossibleState = copy.copy(state)
if chef.possibleAction(ingredient): # Do doAction on state, if true save else trow away
possibleStates.append(newPossibleState)
return possibleStates
Use getattr to get the method you want using a string:
getattr(chef, possibleAction)(ingredient)
chef.possibleAction(ingredient):
This statement indicates that possibleAction() is an instance method belonging either to chef class or its parent class which can be called by chef object.
Ensure that chef class contains the possibleAction method declaration in it or in its parent class.
This question already has answers here:
Python Tkinter Return
(2 answers)
Closed 8 months ago.
I'm currently working on a GUI project on Python (3.6) using tkinter (8.6).
Following this question I'm wondering how to get back the result of someFunction :
def someFunction(event):
do stuff ..
return(otherStuff)
canvas.bind('<Button-1>',lambda event: someFunction(event))
Thank you in advance :) !
The return values of callback functions like your someFunction are ignored. Rather than using return, have the callback save the value somewhere (in a global variable or an attribute of some kind of object). Or have your function pass the computed value as an argument to some other function that will do something with it.
This question already has answers here:
Python - Why is this class variable not defined in the method?
(3 answers)
Why is instance variable not getting recognized
(2 answers)
Closed 6 years ago.
I am writing a piece of code for a homework class, which should allow me to calculate various distance statistics about two lists. However, when I assign the lists to the class, and try to print the result of one of the functions, I get the error,
NameError: name 'ratings1' is not defined
Leading me to believe that I did something incorrectly either in my __init__ function or the referencing in the functions. Can you help clarify what I'm doing wrong?
class similarity:
def __init__(self, ratingX, ratingY):
self.ratings1=ratingX
self.ratings2=ratingY
def minkowski(self,r):
self.r=r
mink=0
length=len(ratings1)
for i in range(0,length):
mink=mink+(abs(ratings1[i]-ratings2[i]))**r
mink=mink**(1/r)
result='Given r=%d, Minkowski distance=%f'%(r,mink)
return result
def pearson(self):
Xavg=average(ratings1)
Yavg=average(ratings2)
n=len(ratings1)
diffX=[]
diffY=[]
for i in range(0,n):
diffX.append(ratings1[i]-Xavg)
diffY.append(ratings2[i]-Yavg)
return diffX
diffXY=[]
for i in range(0,n):
diffXY.append(diffX[i]*diffY[i])
example2=similarity([1,3,5,5,6],[4,6,10,12,13])
print(example2.pearson())
Note: this error persists if I change the references to "ratings1/2" to "ratingsX/Y" in the functions.
You need to use self before every reference to instance variable, ie self.ratings1, and your indentation is wrong as well.
ratings are associated with class. Use self.ratings1 and so on..
I just figured out my mistake. For each function I failed to use the self. phrase before the ratings name. To amend this, I added
ratings1=self.
ratings2=self.ratings2
To the beginning of each function. Problem solved.