用于不同变量的相同方法

时间:2014-01-10 04:33:34

标签: python class variables methods

假设我有一个类和一个方法,如下所示。如果我想对self.two [0]和other.two [0]以及我可能需要的其他任何东西做同样的事情怎么办?什么会替代方法定义中的self.one [0]和other.one [0],我将如何调用此方法?

更新以更好地了解我到目前为止所拥有的内容

class OurClass:

    def __init__(self, name):
        self.name=name
        self.one = (x, y) 
        self.two = (a, z)
         # and so on

    def ourmethod(self, other):
        overall = 0 
        if abs(self.one[1] - other.one[1]) <= 10:
            if abs(self.one[0] - other.one[0]) in [2, 4, 8, 10]:
                overall += 4                
            elif abs(self.one[0] - other.one[0]) in [3, 9]: 
                overall -= 6                
            elif abs(self.one[0] - other.one[0]) == 6:
                overall += 3                        
            elif abs(self.one[0] - other.one[0]) == 0:
                overall += 6        
            else:
                overall += 0
        else:
            overall += 0

1 个答案:

答案 0 :(得分:0)

你可以这样做,保留一个内部类列表,并在初始化时将每个对象添加到列表中,然后有一个内部函数,你可以调用它将一个对象与列表中其余创建的对象进行比较

class OurClass:
    classList = []

    def __init__(self, name):
        self.name=name
        self.one = (x, y) 
        self.two = (a, z)            
        OurClass.classList.append(self)

    def ourmethod(self)
        for n in OurClass.classList:
            if n != self:
                # some stuff happens