Home > Enterprise >  python: exponent special method?
python: exponent special method?

Time:09-22

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'

CodePudding user response:

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...

CodePudding user response:

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)

CodePudding user response:

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 too Foo class for that usage.

  • Related