Jan-24-2019, 08:23 AM
I have added a print in the __init__(), so you can see what is going on:
That said the recommended way to test if an object is instance of certain class/type is
class Opera(object): def __init__(self,opera): self.opera=[] print('print from __init__()', type(opera), type(opera) in (list,tuple)) if type(opera) in (list,tuple): self.opera.extend(opera) def __add__(self, other): return Opera(self.opera+other.opera) def __sub__(self, other): return Opera(p for p in self.opera if p not in other.opera) def __str__(self): return 'Operator overload Example{}'.format(self.opera) p1=Opera(['red','Green','Orange']) p2=Opera(['go','stop']) p3=Opera(['Orange']) print ('p1:'+str(p1)) print ('p2:'+str(p2)) print ('p3:'+str(p3)) print ('p1+p2:'+str(p1+p2)) print ('p1-p3:'+str(p1-p3))
Output:print from __init__() <class 'list'> True
print from __init__() <class 'list'> True
print from __init__() <class 'list'> True
p1:Operator overload Example['red', 'Green', 'Orange']
p2:Operator overload Example['go', 'stop']
p3:Operator overload Example['Orange']
print from __init__() <class 'list'> True
p1+p2:Operator overload Example['red', 'Green', 'Orange', 'go', 'stop']
print from __init__() <class 'generator'> False
p1-p3:Operator overload Example[]
>>>
As you can see (second line from the end) p for p in self.opera if p not in other.opera
on line 11 is a generator expression
, it's not neither list
nor tuple
, so your if condition in the __init__()
is evaluated False
.That said the recommended way to test if an object is instance of certain class/type is
if isinstance(opera, (list,tuple)):
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs