compile error when using override

Steve D'Aprano steve+python at pearwood.info
Thu Dec 1 06:19:45 EST 2016


On Thu, 1 Dec 2016 05:26 pm, Ho Yeung Lee wrote:

> import ast
> from __future__ import division

That's not actually your code. That will be a SyntaxError.

Except in the interactive interpreter, "__future__" imports must be the very
first line of code.


> class A:
>     @staticmethod
>     def __additionFunction__(a1, a2):
>         return a1*a2 #Put what you want instead of this

That cannot work in Python 2, because you are using a "classic"
or "old-style" class. For staticmethod to work correctly, you need to
inherit from object:

class A(object):
    ...


Also, do not use double-underscore names for your own functions or methods.
__NAME__ (two leading and two trailing underscores) are reserved for
Python's internal use. You should not invent your own.

Why do you need this "additionFunction" method for? Why not put this in the
__add__ method?

>   def __add__(self, other):
>       return self.__class__.__additionFunction__(self.value, other.value)
>   def __mul__(self, other):
>       return self.__class__.__multiplyFunction__(self.value, other.value)

They should be:

    def __add__(self, other):
        return self.additionFunction(self.value, other.value)

    def __mul__(self, other):
        return self.multiplyFunction(self.value, other.value)

Or better:

    def __add__(self, other):
        return self.value + other.value

    def __mul__(self, other):
        return self.value * other.value



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.



More information about the Python-list mailing list