繁体   English   中英

必须使用instance作为第一个参数调用unbound方法

[英]unbound method must be called with instance as first argument

我想在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!!!!!')

我不知道,我所做的可以被实例化正确的类,但我用它喜欢, Thefraction.add在侧__name__=='__main__' 我错过了什么?

这意味着这样做:

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

然后在你的班上:

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

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

是的,再次阅读课程教程。 彻底。

你没有把()放在你的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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM