Bla*_*ble 4 python methods object
这可能看起来有点奇怪,但它可以让我方便地完成一些代码.
因为Python方法本身就是对象,所以方法可以有自己的方法吗?也就是说,如果我想执行以下操作(忽略语法):
def methodCaller(someArgs, methodB):
# some stuff here . . .
variableWithAGoodName = methodB()
jonSkeet = methodB.methodC(variableWithAGoodName)
return jonSkeet
Run Code Online (Sandbox Code Playgroud)
可能吗?我的猜测是否定的,但如果方法只是对象,那么它不应该以某种方式存在吗?
非常感谢!
编辑:我认为已经发布,我正在寻找一个高阶函数.
我的问题有点学术性,因为我知道我可以重新组织我的代码以完全不同的方式完成这种方式.但是,实际上,我正在尝试使用Python来学习至少它的基础知识.我还没有尝试过,但由于我不熟悉Python,它可能是有可能的,只是没有这种语法.
另一个编辑:我试图用我的命名搞笑,但它使问题不清楚.为此,我道歉.这是一个更好的例子:
def MethodA(MethodB):
# MethodB is passed as a parameter but is also a method.
# MethodB has a method of its own, somehow, because it is technically still
# an object.
MethodB.MethodC() #Let's pretend it returns nothing here.
# Can this happen?
Run Code Online (Sandbox Code Playgroud)
python中的函数是具有方法和属性的第一类对象.
def foo():
print("foo")
def bar():
print("bar")
foo.bar = bar
foo.bar() #outputs "bar"
foo.baz = "Hello, world!"
print(foo.baz) # outputs "Hello, World!"
Run Code Online (Sandbox Code Playgroud)
编辑:
因为函数是第一类对象,所以您也可以像传递任何其他变量一样传递它们.您还可以编写"高阶函数",它们是函数(或返回函数的函数)的函数.
编辑2:
[对于'没有像S-Club派对那样的派对!''没有像完整代码示例那样的例子!
def higher_order_function (input_function):
input_function.method()
def input_function_1 ():
print ("exec'ing input_function_1()")
def input_function_1_method ():
print ("exec'ing input_function_1_method()")
input_function_1.method = input_function_1_method
higher_order_function(input_function_1)
# prints "exec'ing input_function_1_method"
Run Code Online (Sandbox Code Playgroud)