繁体   English   中英

python类方法不同于非类函数

[英]python class method different from non-class function

我怀疑类方法对某些变量集的作用与相应的非类函数的作用不同。 这是一个例子。 假设我们有一组变量: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

我认为,两种方法的结果必须相同。 唯一的区别是变量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

我要说的是,在第一种情况下,每次创建新的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访问这些变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM