0

I'm using Python 3.9.12, trying to dynamically overwrite instance methods on instance creation in init for a class (class A) from another class (class B), but getting unexpected results when doing this for the pow magic method. The overwrite seems to work, but it is not recognized as a magic method. How to allow the new __pow__ method (from class B) to be called in a**2?

For example, defining

class A(object):
    
    def __init__(self, **kwdict):
        ## Set the '__pow__' method in class A from class B
        new_method_name = '__pow__'
        new_method = getattr(B, new_method_name)
        setattr(self, new_method_name, new_method.__get__(B, self.__class__))

    def __pow__(self, other):
        print("Running __pow__ from class A definition.")

        
        
class B(object):
    
    def __init__(self):
        pass
    
    def __pow__(self, other):
        print("Running __pow__ from class B definition.")

and running

a = A()
a**2

gives the output

Running __pow__ from class A definition.

from the original class A method, while running the method directly

a.__pow__(2)

gives the output

Running __pow__ from class B definition.

from the new class B method.

Question: How to return the class B output in both cases?

SuperStormer
  • 4,997
  • 5
  • 25
  • 35
user813869
  • 31
  • 2

0 Answers0