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.
Advertisement
Answer
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.