python: exponent special method?

Question:

what is the special method for exponent? For example:

class Foo:
    def __init__(self,data):
        self.data = data
    def __pow__(self, power):
        return self.data ** power

if __name__ == '__main__':
    f=Foo(2)
    print(f**3)

yields 8 correctly, but when I run 3**f it says: TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'Foo'

Asked By: Sam-gege

||

Answers:

You should’ve used __rpow__ to use like that

Code:

class Foo:
    def __init__(self,data):
        self.data = data
    def __pow__(self, power):
        return self.data ** power
    def __rpow__(self, power):
        return self.data ** power

if __name__ == '__main__':
    f=Foo(2)
    print(f**3) # 8
    print(3**f) # 8

Tell me if its not working…

Answered By: Ghost Ops

Another way would be inheriting the int class:

class Foo(int):
    def __init__(self, x):
        self.x = x
    def __pow__(self, power):
        return self.x ** power

a = Foo(2)
print(2 ** a)
Answered By: Drachen

When you execute f**3, the interpreter automatically calls __pow__ method on the object with the integer you gave it(the __pow__ method is an equivalent for ** operator ), but it can’t interpret any way to use f as the power of a number. So you should define another function inside Foo class for that usage.

Answered By: Mahdi Gheidi
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.