好吧,在面向对象编程时我仍然是初学者,但我不确定为什么我的代码在分配等同于类的临时变量时完全改变了类的属性。
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()
当我赋予临时变量结果等于派生类并更改结果的value属性时,它完全改变了派生的value属性。现在变量temp的值也为0.它应该这样做吗?如何才能使结果的value属性为零,并且temp仍然设置为derived的value属性。
换句话说,最后,我希望c.value为4。
答案 0 :(得分:0)
所以,看起来问题出现在这段代码中:
result = derived
result.value = 0
temp = derived
for i in Input:
temp.value = i.value
result.value = result.value + temp.value
return result
请注意,temp
,result
和derived
都指向同一个对象,并且您多次写入该对象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
如果我们这样做,那么我们可以看到以下主要产生的预期值 4 。
c = setValue(derived(), [L1(), L2()])
print c.value