I want to implement the following functionality:
TestClassvaluesaccepts arbitrary number ofNewClassobjects- Only
NewClassobjects which do not have all the same attribute values get added toTestClass.values
I've come up with this:
class NewClass:
def __init__(self, value1, value2):
self.value1 = value1
self.value2 = value2
class TestClass:
def __init__(self, *values):
self.values = self._set(values)
def _set(self, object_list):
unique_dict = {}
for obj in object_list:
if list(obj.__dict__.values()) not in unique_dict.values():
unique_dict[obj] = list(obj.__dict__.values())
return list(unique_dict.keys())
obj1 = NewClass(1, 2)
obj2 = NewClass(1, 2)
obj3 = NewClass(5, 2)
test = TestClass(obj1, obj2, obj3)
Only obj1 and obj3 are in the test.values
I am wondering how to do it in "protocol" way, such as len or add, etc.
def __len__(self):
return len(self.values)
And does the second approach have meaningful benefits compared to the first one?