python - How to initialize a Vector instance by calling a method, defined in the same class-Vector? -
so want initialize instance ov vector class, tuple return method defined in class.
class point(object): def __init__(self, x, y): self.x = x self.y = y class vector(object): def __init__(self, x, y): self.x = x self.y = y def subtract(self, a, b): x = a.x - b.x y = a.y - b.y return x, y # <-- tuple p = point(0, -1) = point(1, 1) # here want call vector.subtract(p, i) , assign tuple vector instance
i following vector tutorial's, in c++ , syntax there different python have no idea how can this.
why don't rewrite method
def subtract(self, a, b): x = a.x - b.x y = a.y - b.y return x, y # <-- tuple
to
def subtract(self, a, b): x = a.x - b.x y = a.y - b.y return vector(x, y) # <-- tuple
it weird declare instance method substract
, more reasonable make this:
def subtract(self, b): x = self.x - b.x y = self.y - b.y return vector(x, y) # <-- tuple
so can call
a = vector(1,2) b = vector(4,1) c = a.substract(b)
or @ least make static method removing self
reference
@staticmethod def subtract(a, b): x = a.x - b.x y = a.y - b.y return vector(x, y) # <-- result new vector
and use this
c = vector.subtract(a, b)
Comments
Post a Comment