35
1
Your task is to write some code in Python 2 or 3 such that this expression:
(a+b)(c+d) == a*c + b*c + a*d + b*d
will evaluate to True without raising any exceptions.
To clarify, I will copy your code into a file, then from the file import *. Then I will type the expression into the console and verify that it is True.
This is code-golf, so the answer with the shortest length (in bytes) wins.
Nice! There's
0 .__mul__forlambda y:0but it's the same length. – xnor – 2016-10-28T23:28:53.010x.countsaves a byte. – Dennis – 2016-10-28T23:36:31.490With
a=t();b=c=d=0, you can useclass t(int):__add__=lambda*x:tto save three bytes. – Dennis – 2016-10-29T00:24:40.770@Dennis Thanks. Good idea... – jimmy23013 – 2016-10-29T00:32:37.737
1I don't get it...
type(t(), t())ort().type(t())throws an exception, so what is happening when you dot() + t()? – feersum – 2016-10-29T03:56:20.757@feersum just
type(t()). The LHS becomes(type(b))(0)ort(0), which is equal to0. – Jonathan Allan – 2016-10-29T09:59:46.080@JonathanAllan But
+is a binary operator. Why would__add__be called with 1 argument? – feersum – 2016-10-29T10:10:09.4971@feersum
__add__is called with two, but the first is interpreted asself, onlyotheris passed totype. Weird, yes. – Jonathan Allan – 2016-10-29T10:12:28.543@feersum The difference is, I believe, that inbuilts use method-wrappers (py3) or unbound methods (py2) (rather than methods or bound methods respectively, like
MySpam.__myEggs__would usually be). I could well be wrong though, interested to know... – Jonathan Allan – 2016-10-29T10:23:39.453@JonathanAllan But try this:
numargs = lambda *a: len(a); class t(int): __add__ = numargst() + t()results in2! – feersum – 2016-10-29T11:03:56.4701
@feersum:
– user2357112 supports Monica – 2016-10-29T18:25:17.497a + bfirst triesa.__add__(b).a.__add__istype, so that becomestype(b). The key difference between this case and the usual case for methods is that usually,a.__add__would be a different object from the thing you set__add__to in the class definition, due to the descriptor protocol, which ordinary function objects implement. (There are also a few other tricky bits that aren't relevant here.)