I want to create a method that only takes objects of the class it is is defined in, manipulates it and returns a new object of the same class.
For example:
class fraction(): def__init__(self, counter, denominator): self.counter=counter self.denominator=denominator def add(self,(object of class fraction)) (addition of object the method from called in and the object which is called in the method return (new object of the class fraction)
Does anyone have an idea how to get this done? best regards, David
Advertisement
Answer
You can do something like this :
class Fraction: def __init__(self, counter, denominator): self.counter = counter self.denominator = denominator def add(self, fraction): return Fraction(self.counter * fraction.denominator + fraction.counter * self.denominator, self.denominator * fraction.denominator) a = Fraction(2, 3) b = Fraction(3, 5) a_plus_b = a.add(b) print(a_plus_b.counter, a_plus_b.denominator)
You can add type checking directly in the add function :
def add(self, fraction): if not isinstance(fraction, Fraction): raise TypeError(f"{fraction} is not a Fraction.") return Fraction(self.counter * fraction.denominator + fraction.counter * self.denominator, self.denominator * fraction.denominator)
If you want to integrate this in the standard fractions module, you can make a class inheriting from fractions.Fraction, which will outpute you a nice irreductible fraction :
import fractions class MyFraction(fractions.Fraction): def add(self, fraction): return MyFraction(self.numerator * fraction.denominator + fraction.numerator * self.denominator, self.denominator * fraction.denominator) a = MyFraction(2, 3) b = MyFraction(10, 6) a_plus_b = a.add(b) print(a_plus_b.numerator, a_plus_b.denominator)