只接受方法中的对象并返回新对象

ej83mcc0  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(373)

我想创建一个方法,该方法只接受它所定义的类的对象,对它进行操作并返回同一类的新对象。
例如:

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)

有人知道怎么做吗?向你问好,大卫

xienkqul

xienkqul1#

您可以这样做:

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)

您可以在添加功能中直接添加类型检查:

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)

如果要将其集成到标准分数模块中,可以创建一个继承自fractions.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)

相关问题