Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 名称“;函数名";没有定义_Python_Function - Fatal编程技术网

Python 名称“;函数名";没有定义

Python 名称“;函数名";没有定义,python,function,Python,Function,我一直在尝试完成OOP的一个主题,但我无法找出函数定义的错误。我是这门语言的新手,已经在论坛上搜索过了,但是找不到任何有用的东西 错误消息: 回溯(最近一次呼叫最后一次): 文件“/home/main.py”,第44行,在 添加(x,y) 名称错误:未定义名称“添加” 这是我写的程序 class Complex(object): def __init__(self, r = 0, i = 0): self.r = r self.i = i def __str__ (self):

我一直在尝试完成OOP的一个主题,但我无法找出函数定义的错误。我是这门语言的新手,已经在论坛上搜索过了,但是找不到任何有用的东西

错误消息: 回溯(最近一次呼叫最后一次):
文件“/home/main.py”,第44行,在
添加(x,y)
名称错误:未定义名称“添加”

这是我写的程序

class Complex(object):
def __init__(self, r = 0, i = 0):
   self.r = r
   self.i = i

def __str__ (self):
   return "%s + i%s" % (self.r, self.i)

def add (self, other):
   summ = Complex()
   summ.r = self.r + other.r
   summ.i = self.i + other.i
   return "Sum is %d" % summ

def dif (self, other):
   dif = Complex()
   dif.r = self.r - other.r
   dif.i = self.i - other.i 
   return dif

def multiply (self, other):
   multiply = Complex()
   multiply.r = self.r * other.r 
   multiply.i = self.i * other.i
   return "%d" % (-1 * multiply.r * multiply.i)

def divide (self, other):
   divide = Complex()
   divide.r = self.r / other.r
   divide.i = self.i / other.i 
   return "%d" % (divide.r / divide.i)

x = Complex()
y = Complex()
x.r = int(input("Type in real part of x: \n"))
x.i = int(input("Type in imaginary of x: \n"))
print (x, "\n")
y.r = int(input("Type in real part of y: \n"))
y.i = int(input("Type in imaginary of y: \n"))
print (y, "\n")
add(x, y)

如果add是类复合体的一个方法,那么必须编写x.add(y)而不是add(x,y)

我知道在Python中这是令人困惑的。您需要始终应用“self”作为方法的第一个参数,尽管它不是参数,而是您调用其方法的对象。

函数
add()
Complex
类的成员,但您是在自己调用它

你需要这样称呼它

x.add(y)
当函数是类的成员时,如下所示:

class Complex(object):
    def add (self, other):
        # Do stuff
调用函数的对象自动作为
self
传递

因此,如果您调用
x.add(y)
self
将是
x
,而
other
将是
y