So it seems that if you create a class and declare an array in that class outside the __init__()
function, the array will be treated like a class variable (even though you must refer to it as self.array). But it will be treated as an instance variable if you declare it inside the __init__()
.
To be clear, this doesn’t appear to be a Rhino issue but rather a “feature” of the python language (unless I’m doing something wrong). So, this post is more of a caution or helpful info. It had me very puzzled for several hours. It was happening with a custom event, which made me think it had something to do with passing functions between classes or something, but, no, my subscriber list (of handlers) was an array declared outside of the __init__
of my custom class. So all instances would fire the event even though I only subscribed to the event of one instance.
Here is a simple example demonstrating the issue. If you run it, the results (posted below the example) show that that List1 ends up appending words from both instances, while List2 has a separate list for each instance.
#! python3
class WordListCollection:
# this will be treated as a class variable
List1 = []
Name = ""
def __init__(self):
# this will be treated as an instance variable
self.List2 = []
def AddWordsToList1(self, words):
for word in words:
self.List1.append(word)
def AddWordsToList2(self, words):
for word in words:
self.List2.append(word)
WLC1 = WordListCollection()
WLC1.Name = "WordListCollection1"
WLC1.AddWordsToList1(["apple", "pear", "banana"])
WLC1.AddWordsToList2(["Ford", "Chevy", "Dodge"])
WLC2 = WordListCollection()
WLC2.Name = "WordListCollection2"
WLC2.AddWordsToList1(["peach", "cherry", "apricot"])
WLC2.AddWordsToList2(["Mercury", "Pontiac", "Jeep"])
print(WLC1.Name)
print("List1", WLC1.List1)
print("List2",WLC1.List2)
print("")
print("--------------")
print("")
print(WLC2.Name)
print("List1", WLC2.List1)
print("List2", WLC2.List2)
Results:
WordListCollection1
List1 ['apple', 'pear', 'banana', 'peach', 'cherry', 'apricot']
List2 ['Ford', 'Chevy', 'Dodge']
--------------
WordListCollection2
List1 ['apple', 'pear', 'banana', 'peach', 'cherry', 'apricot']
List2 ['Mercury', 'Pontiac', 'Jeep']
5 posts - 3 participants