将类指定为变量

2024-05-08 20:20:31 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我还是一个面向对象编程的初学者,但是我不知道为什么我的代码在为类指定一个等价的临时变量时会完全改变类的属性。你知道吗

class L1:
    value = 3
class L2:
    value = 1
class derived:
    value = 3523

def setValue(derived,Input):

    if len(Input) == 0:
        print 'Error, LIST HAS NO ENTRY'
        return 0
    elif len(Input) == 1:
        derived.value = 1
        return derived
    else:
        result = derived
        result.value = 0
        temp = derived
        for i in Input:
            print result.value
            temp.value = i.value
            print temp.value
            result.value = result.value | temp.value
        return result

def main():
    a = L1()
    b = L2()
    c = derived()
    x = [a,b]
    c = setValue(c,x)

main()

当我将临时变量result赋给派生类并更改result的value属性时,它完全更改了派生类的value属性。现在变量temp的值也为0。它应该这样做吗?如何使结果的value属性为零,并且temp仍然设置为派生的value属性。你知道吗

换句话说,在最后,我希望c.value是4。你知道吗


Tags: l1inputlenreturn属性valuemaindef
1条回答
网友
1楼 · 发布于 2024-05-08 20:20:31

因此,问题似乎在以下代码中:

    result = derived
    result.value = 0
    temp = derived
    for i in Input:
        temp.value = i.value
        result.value = result.value + temp.value
    return result

请注意,tempresultderived都指向同一个对象,您可以多次写入该对象的value。基本上,您当前的循环与以下内容相同:

    derived.value = 0
    for i in Input:
        derived.value = derived.value + derived.value
    return derived

就我个人而言,我不明白为什么这个函数不仅仅是:

def setValue(derived, Input):
    if len(Input) == 0:
        print 'Error, LIST HAS NO ENTRY'
        return None
    elif len(Input) == 1:
        derived.value = 1
        return derived
    else:
        derived.value = sum(x.value for x in Input)
        return derived

甚至只是:

def setValue(derived, Input):
    derived.value = sum(x.value for x in Input)
    return derived

如果我们想把它分解成一个实际的循环,我们会:

def setValue(derived, Input):
    derived.value = 0
    for elem in Input:
        derived.value += elem.value
    return derived

如果我们这样做,那么我们可以看到下面的main将产生您的预期值4。你知道吗

c = setValue(derived(), [L1(), L2()])
print c.value

相关问题 更多 >