In the following, why it is not printing results even though I don't see any errors:
class Test(object):
def __init__(self, x, y):
self.x = x
self.y = y
def printing(self):
var = self.x + self.y
print(" RESULT= %i " % var)
if __name__ == '__main__':
Test().printing(10, 20)
if __name__ == '__main__':
Test().printing(10, 20)
Should be
Test(10, 20).printing()
You have mistake in instance initialization.
Related
enter code here. Can you help me with this code of a custom combobox from 0? I try to call it from gc.bind("\<Button-1\>",menu.mauseDown) but it doesn't show any result when pressing click
I expected the combo box to be displayed I was expecting the combo box to show up but nothing happens when I click the mouse. I tried my best but failed
from tkinter import Tk,Canvas
from Library.Sombreado import cuadricula
from Library.Menu import Lista
def Diseño(gc):
cuadricula(gc,291,100,524,500,18,"v","#566573")
cuadricula(gc,284,100,524,516,18,"h","#566573")
gc.create_polygon(3,3,3,597,290,597,290,100,796,100,796,3,fill="#808080",width=5,outline="Black")
gc.bind("<Button-1>",menu.mauseDown)
menulista=["Simplemte Armada","Doblemente Armada"]
menu=Lista(60,50,175,32,menulista)
def Paint(gc):
Diseño(gc)
menu.pintar(gc)
def Ventana():
Nombre = Tk()
gc=Canvas(Nombre,width=800,height=600,bg="#EBF5FB",highlightbackground="black")
Nombre.iconbitmap("Image\\concrete.ico")
Nombre.title("T-CAS CIVIL")
Nombre.configure(bg="black")
a,h=800,600
x= Nombre.winfo_screenwidth() // 2 - a // 2
y= Nombre.winfo_screenheight() // 2 - h // 2
c = str(a) + "x" + str(h) + "+" + str(x) + "+" + str(y)
Nombre.geometry(c)
Nombre.resizable(False,False)
Paint(gc)
Nombre.focus_set()
gc.pack()
Nombre.mainloop()
if __name__ == "__main__":
Ventana()
my menu class that i try to call from my main window
class Lista():
def __init__ (self,x,y,w,h,Lis):
self.x=x
self.y=y
self.w=w
self.h=h
self.Lis=Lis
self.isArea=False
self.lista_cordy={}
self.valor_select=""
self.valor_select2=""
self.No_Elementos=0
self.Cordy = None
def pintar(self,gc):
gc.create_rectangle(self.x,self.y,self.w,self.h,fill="#008080")
gc.create_text(self.x,self.y,text="≡",font=("TI-Nspire",13,"normal"),fill="Black")
if self.valor_select==None:
self.valor_select=""
if self.valor_select=="":
op="Simplemente Armada"
gc.create_text(self.x+self.w/2-len(str(op))/2,self.y,text=str(op),font=("TI-Nspire",12,"normal"),fill="white")
else:
gc.create_text(self.x+self.w/2-len(str(self.valor_select))/2,self.y,text=str(self.valor_select),font=("TI-Nspire",12,"normal"),fill="white")
if self.isArea==True:
for i in range (len(self.Lis)):
gc.create_rectangle(self.x,self.y+i*self.h,self.w,self.h,fill="#ffffff")
gc.create_text(self.x+self.w/2-len(str(self.Lis[i]))/2,self.y+i*self.h,text=str(self.Lis[i]),font=("TI-Nspire",12,"normal"),fill="black")
self.lista_cordy[i]=self.y+i*self.h
if self.Cordy != None :
gc.create_rectangle(self.x+1,self.Cordy+1,self.w-1,self.h-1,fill="#1C86EE")
gc.create_text(self.x+self.w/2-len(str(self.valor_select2))/2,self.y+self.Cordy,text=str(self.valor_select2),font=("TI-Nspire",12,"normal"),fill="#C80000")
def Coordenadas(self,evento):
x,y= evento.x, evento.y
return x >= self.x and x <= self.x + self.w and y >= self.y and y <= self.y + self.h
def mauseDown(self,evento):
x,y= evento.x, evento.y
if self.Coordenadas(evento):
self.isArea = True
else:
for i,v in self.lista_cordy.items():
if y>=v and y<=v+self.h and x>=self.x and x<=self.x+self.w :
self.isArea=False
self.valor_select=self.Lis[i]
self.Cordy=None
def mauseMove(self,x,y):
if self.isArea==True:
for i,v in self.lista_cordy.items():
if y>=v and y<=v+self.h and x>=self.x and x<=self.x+self.w :
self.cordy_n=v
self.valor_select2=self.Lis[i]
if x>=self.x and x<=self.x+self.w and y>=self.y and y<=self.y+self.h+self.h*self.No_Elementos:
pass
else:
self.Cordy=None
I'm writing this code and there is a need to send objects as parameters in functions. My problem is one of the objects needs to be resued with its original values but as I need to return an object from the functions.
I don't know how I can send the answer and keep the original values in the object
safe for reuse. Is there any way to make an object from the class declaration itself?
import math
class Points(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __sub__(self, no):
no.x = no.x - self.x
no.y = no.y - self.y
no.z = no.z - self.z
return(no)
def dot(self, no):
ans = (self.x * no.x)+(self.y * no.y)+(self.z * no.z)
return ans
def cross(self, no):
x = (self.y * no.z)-(self.z * no.y)
y = (self.x * no.z)-(self.z * no.x)
z = (self.x * no.y)-(self.y * no.x)
self.x = x
self.y = y
self.z = z
return(self)
def absolute(self):
return pow((self.x ** 2 + self.y ** 2 + self.z ** 2), 0.5)
if __name__ == '__main__':
points = list()
for i in range(4):
a = list(map(float, input().split()))
points.append(a)
a, b, c, d = Points(*points[0]), Points(*points[1]), Points(*points[2]), Points(*points[3])
x = (b - a).cross(c - b)
y = (c - b).cross(d - c)
angle = math.acos(x.dot(y) / (x.absolute() * y.absolute()))
print("%.2f" % math.degrees(angle))
I want to do something like:
def function_name(self,other)
temp.x = self.x + other.x
temp.y = self.y + other.y
return temp
This way both input objects will have their original values but I don't know how to get that temp.
Thanks everyone who helped. I got the answer to what I was looking. I wanted an object to act as a container that can store the class variables,
and I didn't knew I can just make a new object of the class from within it!
import math
class Points(object):
def __init__(self, x, y, z):
self.x=x
self.y=y
self.z=z
def __sub__(self, no):
return Points((self.x-no.x),(self.y-no.y),(self.z-no.z))
def dot(self, no):
return (self.x*no.x)+(self.y*no.y)+(self.z*no.z)
def cross(self, no):
return Points((self.y*no.z-self.z*no.y),(self.z*no.x-self.x*no.z),(self.x*no.y-self.y*no.x))
def absolute(self):
return pow((self.x ** 2 + self.y ** 2 + self.z ** 2), 0.5)
As you can see using points, i.e the constructor for class Points, I can store the result of any operations and can return it as an object while not altering my input objects.
If what you're trying to do is reuse a variable that you have passed to a class object, you can just duplicate it in your __init__ statement, or in the function where you use it.
e.g
class Foo:
def __init__(self, my_var1, my_var2):
self.my_var1 = my_var1
self.my_var2 = my_var2
def bar(self):
bar_var1 = self.my_var1
bar_var2 = self.my_var2
bar_var1 = bar_var1 + bar_var2
return bar_var1
Although, I am a little confused by why you are attempting to return self in your cross function, as self is a class parameter, and you don't seem to be using it in its intended purpose. If you're confused about how you should be using self, a brief read through the python class tutorial might be helpful. However, barring that, I hope this answers your question.
I'm trying to get a RPN calculator by reusing the class CalculatorEngine as follows. But when I run it, it shows an Attribute Error: 'RPNCalculator' object has no attribute 'dataStack'. How do I solve this?
(I didn't include the Stack class as there'd be too much code.)
class CalculatorEngine(object):
def __init__(self):
self.dataStack = Stack()
def pushOperand(self, value):
self.dataStack.push(value)
def currentOperand(self):
return self.dataStack.top()
def performBinary(self, fun):
right = self.dataStack.pop()
left = self.dataStack.top()
self.dataStack.push(fun(left, right))
def doAddition(self):
self.performBinary(lambda x, y: x + y)
def doSubtraction(self):
self.performBinary(lambda x, y: x - y)
def doMultiplication(self):
self.performBinary(lambda x, y: x * y)
def doDivision(self):
try:
self.performBinary(lambda x, y: x / y)
except ZeroDivisionError:
print("divide by 0!")
exit(1)
def doTextOp(self, op):
if (op == '+'):
self.doAddition()
elif (op == '-'):
self.doSubtraction()
elif (op == '*'):
self.doMultiplication()
elif (op == '/'): self.doDivision()
class RPNCalculator(CalculatorEngine):
def __init__(self):
super(CalculatorEngine, self).__init__()
def eval(self, line):
op = line.split(" ")
try:
for item in op:
if item in '+-*/':
self.doTextOp(item)
elif item in '%':
self.performBinary(lambda x, y: x % y)
else:
self.pushOperand(int(item))
return self.currentOperand()
except ZeroDivisionError:
print 'divide by 0!'
class X(object):
def __init__(self, name):
self._name = name
def doit(self, bar):
print("Hello")
class Y(X):
def __init__(self):
# super(X, self).__init__()
X.__init__(self, "DDXX")
i = X("Yuze")
j = Y()
Or you can use this snippet to fix it.
I am trying to create some custom Python classes for my application. When I try to debug my code I can not pick the instances of my custom classes, I receive the error "Object XXX is not picklable".
I found this page https://docs.python.org/3/library/pickle.html#what-can-be-pickled-and-unpickled but I don't understand how I should implement the methods that make my class picklable.
For example how would you modify the following classes so that I can pick instances of them?
class Point3D:
def __init__ (self, x, y, z):
self.x = x
self.y = y
self.z = z
def move(self, vector):
self.x += vector.x
self.y += vector.y
self.z += vector.z
return
def isValidPoint(self):
isNotValid = False
isNotValid = math.isnan(self.x) or math.isnan(self.y) or math.isnan(self.z)
return not isNotValid
And
class PointCloud3D:
def __init__ (self):
self.points = []
def getNumberOfPoints(self):
return len(self.points)
def addPoint(self, point):
self.points.append(point)
return
def addPointCloud3D(self, additionalPointCloud3D):
for self.point in additionalPointCloud3D:
self.addPoint(point)
def getCloudCenter(self):
numberOfPoints = self.getNumberOfPoints()
centersSumX = 0
centersSumY = 0
centersSumZ = 0
for point in self.points:
centersSumX = centersSumX + point.x
centersSumY = centersSumY + point.y
centersSumZ = centersSumZ + point.z
centerX = centersSumX/numberOfPoints
centerY = centersSumY/numberOfPoints
centerZ = centersSumZ/numberOfPoints
center = Point3D(float(centerX), float(centerY) , float(centerZ))
return center
While here you can find the code that I am trying to debug:
from classDatabase import Point3D, PointCloud3D
testPoint1 = Point3D(1.5, 0.2, 2.3)
testPoint2 = Point3D(3.5, 1.2, 5.3)
testPointCloud3D = PointCloud3D()
testPointCloud3D.addPoint(testPoint1)
testPointCloud3D.addPoint(testPoint2)
Finally a screenshot of the issue:
from threading import *
from random import *
class Ant(Thread):
def __init__(self, x, y):
Thread.__init__(self)
self.x = x
self.y = y
def move(self, x, y):
self.x = x
self.y = y
class Ant_farm():
def __init__(self, x, y):
self.x = x
self. y = y
self.matrix = matrix(x, y)
self.condition = Condition()
def move(self, ant):
with self.condition:
x1, y1 = next_post(ant)
while self.matrix[x1][y1]:
self.condition.wait()
self.matrix[ant.x][ant.y] = False
ant.move(x1, y1)
self.matrix[ant.x][ant.y] = True
self.condition.notify_all()
def next_pos(self, ant):
while True:
choice = {0: (ant.x, ant.y - 1),
1: (ant.x + 1, ant.y),
2: (ant.x, ant.y + 1),
3: (ant.x - 1, ant.y)}
x1, y1 = choice[randrange(0, 4)]
try:
self.matrix[x1][y1]
except IndexError:
pass
else:
return x1, y1
def __str__(self):
res = '\n'
for i in range(self.x):
aux = ''
for j in range(self.y):
aux += str(self.matrix[i][j]) + ' '
aux += '\n'
res += aux
return res
def matrix(x, y):
return [[False for j in range(y)] for i in range(x)]
if __name__ == '__main__':
ant_farm = Ant_farm(7, 7)
for i in range(4):
# t = Ant(target = ant_farm.move)
pass
I want to run move function inside Ant threads. I tried to do:
t = Ant(target = ant_farm.move)
But the interpreter says this:
TypeError: init() got an unexpected keyword argument 'target'
I understand the error, but I don't know how to do what I said.