alexein777
alexein777

Reputation: 31

Is there a way in Python to tell specific function how to manipulate with my class objects?

Can I tell some function from another package how to manipulate with my user-defined class objects?

For example, I have a class:

class Complex:
    def __init__(self, real, imag):
        self.real = real
        self.imag = imag
    // ...

z = Complex(3, 5)

I want somehow to override math.sin() function to work with my complex numbers, like:

z1 = math.sin(z)

This should create new complex number according to the formula: sin(a + bi) = sin(a)*cosh(b) + icos(a)*sinh(b)

Call

print(z1)

should print

/// 10.472508533940392 - 73.46062169567367i 

Is there a way to do it?

Upvotes: 0

Views: 53

Answers (1)

Relandom
Relandom

Reputation: 1039

I would recommend you to write your own method for your class. Otherwise, you can use something called 'monkey patching'.

import math
def sin(x):
    do_stuff...

math.sin = sin

But in my opinion still, it would be a better idea to write a new function for your class

Upvotes: 1

Related Questions