Python 类的外部函数装饰类的内部函数

代码是通过实例化对象去调用类方法实现,现在有个新需求,在不改变业务代码的情况下,我想增加一个装饰器,目的是在调用具体的类方法的时候在去执行装饰器函数

代码范例:

def decorater(func):
    print("This function's name is %s" % func.__name__)
    def wrapper(*args,**kargs):
        return func()
    return wrapper

@decorater
class NEW():
    def showTime(self):
        print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))    

    def showName(self):
        print("My name is Lee.")

NEW().showName()
NEW().showTime()

上述代码是一个函数装饰类的范例,在实例化NEW对象的时候就会执行decorater, 我的目的是,能否只有在调用showName的时候才会去执行decorater?而非每次实例化的时候去执行.向思否的各位大神求助,感谢!

阅读 2.4k
1 个回答
# coding:utf-8
import time


def decorater(cls):

    showName = cls.showName  # 必要的

    def wrapper(*args, **kwargs):
        print("This function's name is %s" % cls.__name__)
        return showName(*args, **kwargs)
    cls.showName = wrapper

    return cls


@decorater
class NEW():
    def showTime(self):
        print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

    def showName(self):
        print("My name is Lee.")


instance = NEW()
print("instanced\n")
instance.showTime()
print("time showed\n")
instance.showName()
print("name showed")

//instanced

//2018-11-26 16:53:40
//time showed

//This function's name is NEW
//My name is Lee.
//name showed

稍微改了一下,不是特别清楚你究竟想干什么,这样也许不能完全匹配业务.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进