Python Class shows name not defined [duplicate] - python

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.

Related

PyCharm - Shadows name from outer scope [duplicate]

This question already has answers here:
Shadows name xyz from outer scope
(5 answers)
What is the problem with shadowing names defined in outer scopes?
(10 answers)
Closed 1 year ago.
I am learning Python and am trying to take concepts that I learn from video tutorials and add to them. I just watched a video on If Statements and Comparisons, and I wanted to add to what was done in the video by getting input from the user. I received the "shadows name 'ans' from outer scope" warning and have seen others ask this question on the site, but their examples do not involve getting input from the user. Thank you in advance for your help!
ans = input("What color is the sky? ")
def color(ans):
if ans == str("Blue"):
return str("Correct!")
else:
return str("Incorrect.")
print(color(ans))
First things first - the warning is specific to pycharm and your code should run correctly as it is.
Now, there are two ways how you can get rid of the warning:
Either you can rename the argument used within the function i.e. instead of giving it same name ans, you can opt for a different name e.g. answer.
The other way could be suppress this warning in pycharm:
# noinspection PyShadowingNames
def color(ans):
# rest of the code...

Call a stored method on a object [duplicate]

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.

python see the full definition from the name of the function [duplicate]

This question already has answers here:
How can I get the source code of a Python function?
(13 answers)
Closed 4 years ago.
I recently asked a question with title "python find the type of a function" and got very helpful answers. Here is a related question.
Suppose I import *.py files written by me, and these imports result in f being one of the functions defined by me. Now I write to my python interpreter x = f. Later, I want to see the full definition of f, preferably with comments still in place, knowing only x. Is this possible? Does python remember which file the definition was imported from, which is, of course, not enough to give the full definition of f, unless one can find the actual relevant definition?
The built in help(object) will give you the correct documentation if you alias k to some function you commented - same for inspect.getsource(k) - they know which function is ment by your variable name alias k at this time.
See:
the help() built in
inspect.getsource(k)
(taken from here)
Example:
# reusing this code - created it for some other question today
class well_documented_example_class(object):
"""Totally well documented class"""
def parse(self, message):
"""This method does coool things with your 'message'
'message' : a string with text in it to be parsed"""
self.data = [x.strip() for x in message.split(' ')]
return self.data
# alias for `parse()`:
k = well_documented_example_class.parse
help(k)
Prints:
Help on function parse in module __main__:
parse(self, message)
This method does coool things with your 'message'
'message' : a string with text in it to be parsed
Same goes for inspect.getsource(k):
# from https://stackoverflow.com/a/52333691/7505395
import inspect
print(inspect.getsource(k))
prints:
def parse(self, message):
"""This method does coool things with your 'message'
'message' : a string with text in it to be parsed"""
self.data = [x.strip() for x in message.split(' ')]
return self.data
You should think of the way Python uses variables. You have objects (can be classes, functions, lists, scalars or whatelse) and variables that only hold references to those objects.
That explains why when multiple variables point to the same mutable object, if you change it through one of those variables, the change in visible in all other ones.
This is the same thing here. The function object manages all its attributes: its docstring, its code, and its source (if it has: C function show no source). Assigning the function to a new variable does not hide the object behind anything: you still access the original object.
Things would go differently with decorators, because the decorator creates a new object, and the original object is only available to the decorated one.

local methods in a class (python) [duplicate]

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.

Turning a string into variable or object, Python [duplicate]

This question already has answers here:
How to give column name dynamically from string variable in sql alchemy filter?
(4 answers)
Closed 5 years ago.
I've had this problem in the past and never found the solution. I've checked ton's of google links and still don't know.
What I want to do is use a string as a variable. I'm working with SQLalchemy so will use the example straight from my project: (look for the variable 'objective' in the function)
Here's an example:
def win_ratio_p_obj(objective):
#want to find the win/loss ratio for each obj_first, ie. 60% of times when team gets fblood you also win vs. 40% of time you lose
obj_totals = session.query(Match.win, func.count(Match.win)).filter(Match.**objective** == 't').group_by(Match.win).order_by(Match.win).all()
win_chance = obj_totals[1][1]/(obj_totals[0][1]+obj_totals[1][1])
return win_chance
objective = 'first_dragon'
x = win_ratio_p_obj(objective)
objective = 'first_blood'
y = win_ratio_p_obj(objective)
objective = 'first_turret'
z = win_ratio_p_obj(objective)
objective = 'first_inhib'
Returns:
Traceback (most recent call last):
Python Shell, prompt 15, line 1
builtins.AttributeError: type object 'Match' has no attribute 'objective'
So what I want to do is use each objective as a variable name with the aim of reducing code repetition. I know I could very easily copy paste the function a few times but that seems silly.
At the moment the code above won't recognise the objective variables values as variables instead of strings.
Any answers will be super well appreciated!
It seems like you could use getattr:
getattr(Match, objective)

Categories

Resources