python类方法不同于非类函数

时间:2012-06-25 13:46:35

标签: python class function methods scope

我怀疑类方法对某些变量集的动作与相应的非类函数的动作不同。这是一个例子。假设我们有一组变量:A,B,C,我们希望根据一些算法随时间修改它们。有两种可能的实现方式:

1)与班级:

   class variables:
       def __init__(self):
           self.A = 0.0
           self.B = 0.0
           self.C = 0.0
       def changeA(self):
           self.A = some function of A, B and C         
       def changeB(self):
           self.B = some function of A, B and C
       def changeC(self):
           self.C = some function of A, B and C

多次打电话:

    ob = variables()
    i = 0 
    while i<N:
        ob.changeA()
        ob.changeB()
        ob.changeC()
        i = i + 1

2)没有课程

    A, B, C = 0.0, 0.0, 0.0
    def changeA(A,B,C):
        A = some function of A, B and C (same as in class method)
        return A
    def changeB(A,B,C):
        B = some function of A, B and C (same as in class method)
        return B
    def changeC(A,B,C):
        C = some function of A, B and C (same as in class method)
        return C

多次打电话:

    i = 0 
    while i<N:
        A = changeA(A,B,C)
        B = changeB(A,B,C)
        C = changeC(A,B,C)
        i = i + 1

在我看来,2种方法的结果必须相同。唯一的区别是变量A,B和C已知的命名空间(对象本地或函数实现全局 - 但在这两种情况下,方法都可以访问所需的变量)。但是,两种方法的结果似乎不同。所以我的问题是我在类方法实现/理解中缺少什么?

更具体地说,方法的实现示例是changeA:

作为课程方法:

    (... inside the class)
    def changeA(self):
        self.A = self.A + 2.0*self.B - 3.0*self.C*(self.B-self.A)

作为一项功能:

    def changeA(A,B,C):
        A = A + 2.0*B - 3.0*C*(B-A)
        return A

1 个答案:

答案 0 :(得分:0)

我会说在第一种情况下,每次创建新的variables实例时,ABC的值都会重置,这是不是第二种方法中的情况,它们似乎是全球性的。根据您使用这些实例的方式,结果可能会受到影响。

在评论中的OP问题之后

编辑:,以下是如何定义类变量:

>>> class Variables:
    A = 0.0
    B = 0.0
    C = 0.0

    def changeA(self):
           Variables.A = Variables.A + Variables.B * Variables.C


>>> v = Variables()
>>> v.changeA()
>>> v.A
0.0
>>> Variables.A
0.0
>>> 

如您所见,无需再定义__init__方法。您可以instance.Aclass.A访问这些变量。