[英]Name “function name” is not defined
I've been attempting to complete one of my subjects for the OOP, but I couldn't manage to figure out what's wrong with the definition of my functions. 我一直试图完成OOP的一个主题,但我无法弄清楚我的函数定义有什么问题。 I'm a newbie in this language, already searched the forums but I couldn't find anything useful.
我是这种语言的新手,已经搜索过论坛,但我找不到任何有用的东西。
Error message: Traceback (most recent call last):
错误消息:回溯(最近一次调用最后一次):
File "/home/main.py", line 44, in文件“/home/main.py”,第44行,in
add(x, y)添加(x,y)
NameError: name 'add' is not definedNameError:未定义名称“add”
This is the program I wrote. 这是我写的程序。
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)
The add()
function is a member of the Complex
class but you are calling it on its own. add()
函数是Complex
类的成员,但您自己调用它。
You need to call it like this 你需要这样称呼它
x.add(y)
When a function is a member of a class like below: 当函数是类的成员时,如下所示:
class Complex(object):
def add (self, other):
# Do stuff
The object the function is called on automatically gets passed as self
. 调用该函数的对象自动作为
self
传递。
So if you call x.add(y)
, self
will be x
and other
will be y
. 因此,如果你调用
x.add(y)
, self
将是x
而other
将是y
。
If add is a method of your class Complex, then you must write x.add(y) instead of add(x, y). 如果add是类Complex的方法,则必须编写x.add(y)而不是add(x,y)。
I know that it is confusing in Python. 我知道它在Python中令人困惑。 You need always to apply the "self" as first argument of a method, although it is not an argument, but the object whose method you call.
您总是需要将“self”应用为方法的第一个参数,尽管它不是参数,而是您调用其方法的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.