如何通过列表更改类的属性?

问题描述 投票:0回答:2
class myobject:
    attrib = 0

我有这门课,我把

myobject.attrib
放入这样的列表中。 我尝试通过列表更改可变类

thelist = [object(), myobject.attrib]

thelist[1] = 1
print(myobject.attrib)

问题是

myobject.attrib
仍然显示为
0
而不是
1

我怀疑它基本上改变了

1
的索引
thelist
。如何更改列表中类的属性?

python python-3.x class properties attributes
2个回答
0
投票
class myobject:
    attrib = 0
    attrib_2 = 0
    

# The id() function returns a unique id for the specified object.The id is based on object's memory address.
print("Id of myobject.attrib : ",id(myobject.attrib))
print("Id of myobject : ",id(myobject))


# Passing myobject as third value.
thelist = [object(), myobject.attrib,  myobject]

print("Id of list[1] : ",id(thelist[1])) # => here it reffers to integer memory in myobject.attrib.
print("Id of list[2] : ",id(thelist[2])) # => here it reffers to memory of myobject 

thelist[1] = 1
print("Id after changing value attrib : ",id(thelist[1])) # => One's reassigned, Immutable object int memmory changes to a new location, which don't have any reference to myobject.

thelist[2].attrib_2 =1 #Change the value of attrib_2 in myobject as the thelist[2] referes to it's memory since it's mutable.
print("Id after changing value myobject.attrib_2: ",id(thelist[2])) # => Id will be same as the memmory doesn't change. 

print("No change :", myobject.attrib)
print("Changed :", myobject.attrib_2)

0
投票

MyObject 类: 属性 = 0

列表 = [MyObject(), MyObject.attrib]

MyObject.attrib = 1

打印(MyObject.attrib)

这个对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.