![]() |
Class member become static - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Class member become static (/thread-40729.html) |
Class member become static - Quasar999 - Sep-14-2023 In the following code data must be an non static attribute of the class Node: class Node: total = 0 def __init__(self,parent,data): Node.total=Node.total+1 self.index=Node.total self.data = data if self.index!=1: self.parent = parent.index self.depth=parent.depth+1 else: self.parent=1 self.depth=0 list=[Node(0,[2,2,2,2,2,2])] i=0 while list[i].depth<2: for j in range(0,6): p_data=list[i].data num=p_data[j] if num!=0: p_data[j]=0 for k in range(1,num+1): p_data[(j+k)%6]=p_data[(j+k)%6]+1 list.append(Node(list[i],p_data)) i=i+1For every class instance in list all member have the same value for member data and also become static. RE: Class member become static - deanhystad - Sep-16-2023 Do not use "list" as a variable name. list() is a built-in function that creates a list. There are no "static" variables in Python. "total" is a class variable. Your problem is here: p_data=list[i].datap_data and list[1].data are the same list object. Even though "data" is an instance variable that references a list, all instances of Node end up referencing the same list object. Do you want each node to have their own list? You could do this: p_data=list[i].data.copy()Now p_data and list[1].data are different lists. They have the same contents, but they are different list objects. When you create a new Node using pdata, the data in the old Node and the new Node will be different lists. |