samedi 25 août 2018

Is it bad form to override the "dot" operator in Python?

Usually, a period in Python denotes class membership:

class A:
    a = 1

>>> A.a
1

Sometimes the language doesn't seem quite flexible enough to completely express an idea from domains outside of computer science though. Consider the following example which (fairly brittly for brevity) uses the same operator to seem like something completely different.

class Vector:
    def __init__(self, data):
        self.data = list(data)

    def dot(self, x):
        return sum([a*b for a, b in zip(self.data, x.data)])

    def __getattr__(self, x):
        if x == 'Vector':
            return lambda p: self.dot(Vector(p))
        return self.dot(globals()[x])

Here we've taken over __getattr__() so that in many scenarios where Python would attempt to find an attribute from our vector it instead computes the mathematical dot product.

>>> v = Vector([1, 2])
>>> v.Vector([3, 4])
11

>>> v.v
5

If such behavior is kept restricted in scope to the domain of interest, is there anything wrong with such a design pattern?

Aucun commentaire:

Enregistrer un commentaire