I am having trouble assigning different indexes to variables over a function in python. For example, if i have coordinates for points in 3D space and want to assign a name to a variable in a function, lets say "point_1", how do i do that?
Looking at this code:
side_1_point = (1.0,1.0,15.0)
side_1_face = boxPart.faces.findAt((side_1_point,))
side_1_region = regionToolset.Region(faces=(side_1_face))
side_2_point = (17.0,1.0,15.0)
side_2_face = boxPart.faces.findAt((side_2_point,))
side_2_region = regionToolset.Region(faces=(side_2_face))
side_3_point = (18.0,1.0,14.0)
side_3_face = boxPart.faces.findAt((side_3_point,))
side_3_region = regionToolset.Region(faces=(side_3_face))
How can i define a function as:
def assign_face(coord1,coord2,coord3,index)
side_(index)_face = boxPart.faces.findAt((coord1,coord2,coord3,))
return side_(index)_face
I am struggling to find the right syntax.
Thank you
Related
I am trying to understand what does this class
class undo:
def __init__(self, ss):
self.ss = ss
In my head it should simply put the value of ss uniquely in the variables i decide to use,but when I'm using it it rewrites all the variables, as if it was shared.
sum_expenses[100][0] = 100
sum_expenses[99][2] = 99
s = 1
a = [0 for i in range(100)]
a[s] = undo(sum_expenses)
output(a[1].ss)
sum_expenses[100][0] = 0
b = undo(sum_expenses)
print " "
print b.ss
print " "
sum_expenses[99][2] = 1
a[2] = undo(sum_expenses)
print a[2].ss
I do not understand why it overwrites all the variables with the current values of sum_expense, when I try to put it individually so that I can use the past values of sum_expenses.
Thank you and have a good day!
It happens because you're giving __init__ a reference to the list. If you change the list somewhere else, the reference in .ss still points to the same list, so the changes are visible there, too.
You could copy the list, since it's 2D try deepcopy.
Everytime you call this function it overrides reference to thr whole array ss, changing it to the new one you just passed to the constructor.
You can also create this array within the class and pass indexes and value to it like so:
undo.add(index1,index2,value)
Or you can make another variable ss_old and have make the function return that variable before you set it to a new value.
I understand that functions are useful for code which will be used multiple times so I tried creating a function to save myself time and make my code look neater. The function I had looks like this:
def drawCard():
drawnCard = random.choice(cardDeck)
adPos = cardDeck.index(drawnCard)
drawnCardValue = cardValues[adPos]
However, I am not sure how to return these variables as they are local(?). Therefore, I can not use these variables outside the function. I am just wondering if someone could help edit this function in a way where I could use the drawnCard and drawnCardValue variables outside the function?
Use return:
def drawCard():
drawnCard = random.choice(cardDeck)
adPos = cardDeck.index(drawnCard)
drawnCardValue = cardValues[adPos]
return drawnCard, drawnCardValue
drawnCard, drawnCardValue = drawnCard()
Note, you could also write drawCard this way:
def drawCard():
adPos = random.randrange(len(cardDeck))
drawnCard = cardDeck[adPos]
drawnCardValue = cardValues[adPos]
return drawnCard, drawnCardValue
These two functions behave differently if cardDeck contains duplicates, however. cardDeck.index would always return the first index, so drawnCardValue would always correspond to the first item which is a duplicate. It would never return the second value (which in theory could be different.)
If you use adPos = random.randrange(len(cardDeck)) then every item in cardValue has an equal chance of being selected -- assuming len(cardValue) == len(cardDeck).
The below script asks the user an input and open a window in consequence. Then I want to get the informations from the window and put them in a list of list or something like that in order to create an object of the class "Parameter". Everything works except when I try to extract the data with Entry.get to put them in a list of list.
class Parameter (object):
def __init__(self,number_individuals_classes,payoff):
self.nb_classes = number_individuals_classes
self.payoff = payoff
def __repr__(self):
print('nc.classes: {} | payoff: {}'.format(self.nb_classes,self.payoff))
def get_parameters ():
def get_payoff():
global payoff
payoff = []
for i in xrange(len(entr)):
payoff.append(map(Entry.get, entr[i]))
fen1.destroy()
number_individual_classes = input('Number of individual classes: ')
fen1 = Tk()
fen1.title('Enter payoff matrices')
header1 = Label(fen1,text='Cooperation').grid(row=0,column=2)
header2 = Label(fen1,text='Defection').grid(row=0,column=3)
other_txts = []
focal_txts = []
vert_cop_def_txts = []
entr = []
iteration = 0
for focal in range(1,number_individual_classes):
for other in range(focal+1,number_individual_classes+1):
focal_txts.append(Label(fen1,text='Effect on: {}'.format(focal)).grid(column=0,row=3*iteration+2))
vert_cop_def_txts.append((Label(fen1,text='Cooperation').grid(column=1,row=3*iteration+2),Label(fen1,text='Defection').grid(column=1,row=3*iteration+3)))
other_txts.append(Label(fen1,text=' '*65 +'Co-player: {}'.format(other)).grid(row=3*iteration+1,column=2))
entr.append((Entry(fen1).grid(row=iteration*3+2,column=2),Entry(fen1).grid(row=iteration*3+2,column=3),Entry(fen1).grid(row=iteration*3+3,column=2),Entry(fen1).grid(row=iteration*3+3,column=3)))
iteration+=1
Button(fen1,text='Done',command=get_payoff).grid()
fen1.mainloop()
to_return = Parameter(number_individual_classes,payoff)
return to_return
a=get_parameters()
What am I doing wrong ?
Update:
This work. what is the difference ?
from Tkinter import *
def super_function():
out = map(Entry.get, entr)
fen1.destroy()
print out
fen1 = Tk()
entr = []
for i in xrange(10):
entr.append(Entry(fen1))
entr[i].grid(row=i+1)
Button(fen1, text = 'store everything in a list', command = super_function).grid()
fen1.mainloop()
P.s As I am a beginer, any other advice on my script is more than welcome :)
I am not really sure what you intend to do with this, it seems like you want to establish some kind of interaction matrix between each "individual class" but I may be wrong.
First, your function doesn't have any argument ( get_payoff() ), since you want it to extract something from entr, I would assume that you would want to put entr as an argument of your function!
Something like :
Button(fen1,text='Done', command=lambda : get_payoff(entr)).grid()
"lambda" will allow the function to be used without being called when the button is initially created in the GUI.
Second, when I execute (with the modification), I've got an error because in the function you will try to do the get() with None types variables. Your variable "entr" where you want to extract the data contains only None types, not textvariables from Entry widget. The reason is that you can't store widgets in an array like this. Each time you want to create an entry, you must create a variable (a textvariable) which will be the link to the entry:
# a is a string variable
a = StrVar()
# which is linked to the Entry "test"
test = Entry(window, textvariable = a)
# get the variable in Entry "test"
b = test.get()
# print on screen the result
print b
I don't know if that can help you or if I am completely off the mark here.
The first and most important problem is that you are appending to the lists the result of the calls to grid (which is always None), instead of the widget:
focal_txts.append(Label(fen1,...).grid(...))
# ...
This should be:
focal_label = Label(fen1,...)
focal_label.grid(...)
focal_txts.append(focal_label)
Besides, you are trying to use payoff as a global variable, but there is no global name payoff before you use it in your callback function. So when you try to use it as an argument for the constructor of Parameter, it is not within the same scope.
In general, the creation of the widgets dinamically can be improved and the organization of your code would be much better if you use classes.
I am new to python and have a difficulty getting an object to be stored and access in an array or a list in Python.
I've tried doing something like this:
class NodeInfo:
def __init__(self, left, value, right):
self.l = left
self.r = right
self.v = value
tree[0] = NodeInfo(0,1,2)
tree[0].l = 5
tree[0].r = 6
tree[0].v = 7
When I try to assign values to or try to read from the variable, I get the following error:
tree[0] = NodeInfo(0,1,2)
NameError: name 'tree' is not defined
What am I doing wrong, or is there a different way to assign and read objects from arrays or lists in Python.
You need to create list first and use append method to add an element to the end of it.
tree = []
tree.append(NodeInfo(0,1,2))
# or
tree = [NodeInfo(0,1,2)]
I want to use a while loop to initialize class objects with a simple incremented naming convention. The goal is to be able to scale the number of class objects at will and have the program generate the names automatically. (ex. h1...h100...h1000...) Each h1,h2,h3... being its own instance.
Here is my first attempt... have been unable to find a good example.
class Korker(object):
def __init__(self,ident,roo):
self.ident = ident
self.roo = roo
b = 1
hwinit = 'h'
hwstart = 0
while b <= 10:
showit = 'h' + str(b)
print(showit) #showit seems to generate just fine as demonstrated by print
str(showit) == Korker("test",2) #this is the line that fails
b += 1
The errors I get range from a string error to a cannot use function type error.... Any help would be greatly appreciated.
If you want to generate a number of objects, why not simply put them in an array / hash where they can be looked up later on:
objects = {}
for b in range(1,11):
objects['h'+str(b)] = Korker("test", 2)
# then access like this:
objects['h3']
Of course there are ways to make the names available locally, but that's not a very good idea unless you know why you need it (via globals() and locals()).
Variables are names that point to objects that hold data. You are attempting to stick data into the variable names. That's the wrong way around.
instead of h1 to h1000, just call the variable h, and make it a list. Then you get h[0] to h[999].
Slightly different solution to viraptor's: use a list.
h = []
for i in range(10):
h.append(Korker("test",2))
In fact, you can even do it on one line with a list comprehension:
h = [Korker("test", 2) for i in range(10)]
Then you can get at them with h[0], h[1] etc.