2013-10-24 15 views
-1

我想添加兩組座標使用python中的類。這是我迄今爲止所擁有的。使用類在Python中添加兩組座標?

class Position: 
def __init__(self, x, y): 
    self.x = x 
    self.y = y 

def add(self, x): 
    self.x = self + x 

而且在不同的程序來運行I類有

A = Position(1, 1) 
B = Position(2, 3) 
A.add(B) 
A.print() 

所以我嘗試添加A和B來獲得(3,4)。我將如何使用add類來做到這一點?我不知道要爲參數設置什麼或爲了使其工作而在函數的主體中放置什麼。由於

回答

8

轉換添加要

def add(self, other): 
    self.x = self.x + other.x 
    self.y = self.y + other.y 

也就是說,通常很有用不可變對象的工作,所以爲什麼不添加返回一個新的位置

def add(self, other): 
    return Position(self.x + other.x, self.y + other.y) 

然後,如果你真的想得到時髦,爲什麼不重寫__add__()

def __add__(self, other): 
    return Position(self.x + other.x, self.y + other.y) 

這會讓你增加兩個po使用'+'運算符一起整合。

a = Position(1, 1) 
b = Position(2, 3) 
c = a + b 
0

那麼,我不完全確定你是否真的想改變你的觀點。如果你想改變你的觀點,我會做

class Position: 
    def __init__(self,x,y): 
     self.x = x 
     self.y = y 
    def add(self,other): 
     self.x += other.x 
     self.y += other.y 

另外,和更普遍(的職位,我會說,你想爲一個新的位置)

class Position: 
    def __init__(self,x,y): 
     self.x = x 
     self.y = y 
    def __add__(self,other): 
     return Position(self.x + other.x, self.y + other.y) 

這這樣,如果你推翻__eq__

Position(1,2) + Position(3,4) == Position(4,6) 
0

你想是這樣的:

class Position(object): 

    def __init__(self, x, y): 
     self.x = x 
     self.y = y 

    def __add__(self, other): 
     "Add two Positions and return a new one." 
     return Position(self.x + other.x, self.y + other.y) 

    __radd__ = __add__ 

    def __iadd__(self, other): 
     "In-place add += updates the current instance." 
     self.x += other.x 
     self.y += other.y 
     return self 

    def __str__(self): 
     "Define the textual representation of a Position" 
     return "Position(x=%d, y=%d)" % (self.x, self.y) 

    __repr__ = __str__ 

現在你Position類可以使用常規的Python +運營商使用常規print聲明中並打印:

A = Position(1, 2) 
B = Position(2, 3) 
A += B 
print(A) 
0

你可能只想import numpy和使用numpy.array不是滾動自己Position類。

相關問題