Re: [问题] function物件可以透过class呼叫吗

楼主: skyconquer (梅郭曲)   2020-08-22 10:27:06
我把原Po文章放在底下,方便对照。
试试我写的程式码, 看看有无达成你的需求。
麻烦特别注意一下注解的部份︰
******************************************************************************
def nonMemberFunc(arg):
print("nonMemberFunc is called with arg: " + str(arg))
class Logger(object):
def __getfunc__(self, func, arg):
print(func.__name__)
## 移除"func()"的括号,将传入的func变成object并
## 呼叫其 member "__name__"
print(func)
## 移除"func()"的括号,将传入的func变成object并
## 印出其资讯
return func(arg)
def method1(self, arg):
print("method1 is called with argument: "+str(arg) + "\n")
def method2(self, arg):
print("method2 is called with argument: "+str(arg) + "\n")
def method3(self, arg):
print("method3 is called with argument: "+str(arg) + "\n")
if __name__ == "__main__":
L1 = Logger()
L1.__getfunc__(L1.method1, "m1")
L1.__getfunc__(L1.method2, "m2")
L1.__getfunc__(L1.method1, "m3")
L1.__getfunc__(nonMemberFunc, "nonMemberFuncArg")
******************************************************************************
输出结果:
method1
<bound method Logger.method1 of <__main__.Logger object at 0x7f0ff113b9d0>>
method1 is called with argument: m1
method2
<bound method Logger.method2 of <__main__.Logger object at 0x7f0ff113b9d0>>
method2 is called with argument: m2
method1
<bound method Logger.method1 of <__main__.Logger object at 0x7f0ff113b9d0>>
method1 is called with argument: m3
nonMemberFunc
<function nonMemberFunc at 0x7f0ff112c1f0>
nonMemberFunc is called with arg: nonMemberFuncArg
※ 引述《XperiaZ6C (索尼)》之铭言:
: Python一个很方便的功能是函数可以当作参数传递
: 那请问我可以在class里面取得调用的函数物件吗
: 例如我想做到在函数被调用前
: 可以做其他处理
: 拿print来举例好了
: 像是下面程式码这样
: class Logger(object):
: def int(self, value):
: print('Call int()')
: return int(value)
: def float(self, value):
: print('Call float()')
: return float(value)
: logger = Logger()
: logger.int('123')
: logger.float('123')
: 我只知道可以用下面的方法取得函数的名称
: class Logger(object):
: def __getattr__(self, name):
: print('Call %s()' % name)
: 但是函数物件要怎么抓?
: 像是如果我有20个函数的话
: 那class里面就要写20遍
: 如果之后又需要扩充到40个函数
: 那就还要在class里面加40个
: 有没有什么方法是可以把logger.func()里的func()直接抓来用的
: 例如什么
: class Logger(object):
: def __getfunc__(self, func, arg):
: # do something
: return func(arg)
: 之类的
: 这样我只要定义一个函数
: 后面不过扩充几个需要做一样处理的函数
: 我都不需要再增加class里面的函数数量
: 感谢
:
作者: gmccntzx1 (o.O)   2020-08-22 10:33:00
疴,这样并没有达到原 PO 要的那种呼叫方式呀从他的回文来看,要的呼叫方式应该是 `logger.func()`但是那个 `func` 并不在 logger 内你可以看上一篇我贴的那个,不过还是等原 PO 说明吧对,我对后来回文的理解是这样只是这种做法很少见,所以我才想说等原 PO 说明他实际上想做什么功能一般来说也会用类似你这种的方式或前篇 TitanEric 提到的 decorator 去做,因为这样也能处理 caller argument
作者: XperiaZ6C (真●安卓轻旗舰)   2020-08-22 11:55:00
拍谢,我好像整个会错意了,有更新在原文

Links booklink

Contact Us: admin [ a t ] ucptt.com