必须以实例作为第一个参数调用未绑定方法

2024-05-14 00:15:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在python2.x中构建简单的分数计算器

from fractions import Fraction
class Thefraction:

    def __init__(self,a,b):
        self.a = a
        self.b =b
    def add(self):
        return a+b
    def subtract(self,a,b):
        return a-b
    def divide(self,a,b):
        return a/b
    def multiply(self,a,b):
        return a/b

if __name__=='__main__':
    try:
        a = Fraction(input('Please type first fraction '))
        b = Fraction(input('Please type second fraction '))
        choice = int(input('Please select one of these 1. add 2. subtract 3. divide 4. multiply '))
        if choice ==1:
            print(Thefraction.add(a,b))
        elif choice==2:
            print(Thefraction.subtract(a,b))
        elif choice==3:
            print(Thefraction.divide(a,b))
        elif choice==4:
            print(Thefraction.multiply(a,b))
    except ValueError:
        print('Value error!!!!!')

我不确定是否生成了可以实例化的正确类,但是我在__name__=='__main__'的旁边使用了Thefraction.add。我错过什么了吗?


Tags: selfaddinputreturnifdefmultiplyprint
3条回答

你没有把()放在theFraction对象前面。即使你这样做了,你也将面临另一场灾难..你用两个变量(a,b)初始化你的对象,这意味着你将像

Thefraction(a,b).add(a,b)

我不认为您需要这样做,因为ab是每个方法中的局部变量。。这是一种你不需要的变量。 我想你想要的是这个。

  Thefraction(a,b).add()

这是完整的代码

from fractions import Fraction
class Thefraction:

    def __init__(self,a,b):
        self.a = a
        self.b =b
    def add(self):
        return self.a+ self.b
    def subtract(self):
        return self.a-self.b
    def divide(self):
        return self.a/self.b
    def multiply(self):
        return self.a/self.b

if __name__=='__main__':
    try:
        a = Fraction(input('Please type first fraction '))
        b = Fraction(input('Please type second fraction '))
        choice = int(input('Please select one of these 1. add 2. subtract 3. divide 4. multiply '))
        if choice ==1:
            print(Thefraction(a,b).add())
        elif choice==2:
            print(Thefraction(a,b).subtract())
        elif choice==3:
            print(Thefraction(a,b).divide())
        elif choice==4:
            print(Thefraction(a,b).multiply())
    except ValueError:
        print('Value error!!!!!')

如果您想像使用它一样使用它,应该将类方法定义为@classmethod,而不需要init:

class TheFraction:
    @classmethod
    def add(cls, a, b):
        return a+b

这种声明方法的方式表示它们不会在类的实例中运行,但可以如下调用:

TheFraction.add(a, b)

应该这样做:

thefraction = Thefraction(a, b)
if choice == 1:
    print(thefraction.add())

那么在你们班上:

def add(self):
    return self.a + self.b

等等。不要将ab作为参数包含在方法中。

是的,再复习一遍关于课程的教程。彻底的。

相关问题 更多 >