python函数参数搞砸了

kam*_*lot 1 python parameters function

所以我有

def gcd(a,b):
    if a == 0:
            return b
    while b != 0:
            if a > b:
                    a = a - b
            else:
                    b = b - a
    return a 
Run Code Online (Sandbox Code Playgroud)

但是当我从控制台调用gcd(1,2)时,错误

回溯(最近一次调用最后一次):文件"",第1行,在G.gcd(1,2)中TypeError:gcd()只取2个参数(给定3个)

过来....

这完全没有意义,因为我只提出了两个论点......

我做错了什么?

好吧,所以我删除了其他所有内容,这是我班上唯一的事情:

import random
import math

class RSA:
    def gcd(a,b):
        if a == 0:
            return b
        while b != 0:
            if a > b:
                a = a - b
            else:
                b = b - a
        return a 
Run Code Online (Sandbox Code Playgroud)

问题仍然存在

jps*_*ons 7

您将该函数称为方法.添加"self"作为第一个参数,它将起作用.


Sin*_*ion 5

您尚未发布所有代码.您未发布的代码如下所示:

class SomeClass:

    def gcd(a,b):
        if a == 0:
                return b
        while b != 0:
                if a > b:
                        a = a - b
                else:
                        b = b - a
        return a 

G = SomeClass()
G.gcd(1,2)
Run Code Online (Sandbox Code Playgroud)

在python中,当您定义类成员函数时,类实例会自动传递给函数.将代码更改为如下所示:

class SomeClass:

    def gcd(a,b):
        if a == 0:
                return b
        while b != 0:
                if a > b:
                        a = a - b
                else:
                        b = b - a
        return a 

G = SomeClass()
G.gcd(1,2)
Run Code Online (Sandbox Code Playgroud)

还是更好

def gcd( a,b):
    if a == 0:
            return b
    while b != 0:
            if a > b:
                    a = a - b
            else:
                    b = b - a
    return a 

gcd(1,2)
Run Code Online (Sandbox Code Playgroud)

一切都会好的.