[英]How can i use a function inside of another function
I am currently playing around with classes and functions since i am not familiar with python and i would like to know how i can get addy(self, addx)
to call addx. 我目前正在玩类和函数,因为我对python不熟悉,我想知道如何让
addy(self, addx)
调用addx。
class test:
def __init__(self, x):
self.x = x
def addx(self):
y = self.x + 10
return y
def addy(self, addx):
z = addx() + 10
return z
one = test(1)
print(one.addy())
line 15, in print(one.addy()) TypeError: addy() missing 1 required positional argument: 'addx' Process finished with exit code 1
第15行,在print(one.addy())中TypeError:addy()缺少1个必需的位置参数:'addx'进程完成,退出代码为1
You need to call self
from within a class method. 您需要从类方法中调用
self
。 self.addx()
Also the addx
parameter on this line shouldn't be there: def addy(self, addx):
另外,这一行的
addx
参数不应该存在: def addy(self, addx):
I think this is what you are going for: 我想这就是你要的:
class test:
def __init__(self, x):
self.x = x
def addx(self):
y = self.x + 10
return y
def addy(self):
z = self.addx() + 10
return z
one = test(1)
print(one.addy())
You've overcomplicated things by wrapping it in a class. 通过将其包装在类中,您使事情变得过于复杂。 Take it out and it'll work (mostly) the way you expect.
取出它,它将(通常)按您期望的方式工作。
def add10(x):
return x+10
def add20(x):
return add10(add10(x))
Since you've wrapped it in the class you've complicated the namespace. 由于将其包装在类中,因此使名称空间变得复杂。 It's no longer called
addx
or addy
, so using those names throws a NameError
. 它不再称为
addx
或addy
,因此使用这些名称将引发NameError
。 You have to use the qualified name instead. 您必须使用限定名称。
class FooBar():
def __init__(self):
self.x = 10
def addx(self):
return self.x + 10 # Note the `self.` before the attribute...
def addy(self):
return self.addx() + 10 # ...and also before the method name.
Methods are always passed their owning object as a first argument when called, which is why we've got def addx(self):
but then call with self.addx()
在调用方法时,方法始终将其拥有的对象作为第一个参数传递,这就是为什么我们要使用
def addx(self):
然后使用self.addx()
进行调用的self.addx()
If you are attempting to relate addx
in the signature of addy
to the method addx
, you can pass the string name of the method and use getattr
: 如果您正试图涉及
addx
中的签名addy
的方法addx
,你可以传递的方法和使用的字符串名称getattr
:
class Test:
def __init__(self, x):
self.x = x
def addx(self):
y = self.x + 10
return y
def addy(self, func):
z = getattr(self, func)() + 10
return z
s = Test(3)
print(s.addy('addx'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.