I've got a class, A, which carries some data in dictionaries.
class A:
def __init__(self, names: set) -> None:
self.d = {name : list() for name in names}
I am looking to define addition for my class, for which I want to return another instance of A with the combined contents of the dictionaries of the two instances of A.
I get that I need define the __add__ method, but since I only want the addition to be defined for the A type, I first want to check that they match types. Ideally I'd want to do this with a `try except for readability, but I've heard that I'm supposed to use an ordinary if statement. I've also got some issues with the TypeError I'm raising, it's coming out weird.
def __add__(self, a2):
if type(self) == type(a2):
# add functionality later
pass
else:
raise TypeError
This is what the addition looks like when it isn't working:
A({'a'}) + 2
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
A({'a'}) + 2
File "C:...test.py", line 20, in __add__
raise TypeError
TypeError
My question is:
Can/should this be done with a try except instead, and should I not be raising a TypeError?
raise TypeError(f"{self} can't be added to {a2}")...