如何在调用构造函数之前使用方法装饰器?

2024-06-03 13:48:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些代码,允许您定义christmas上发生的事情,而不知道底层实现或如何调用方法,例如

# main.py
import lib.person
person = lib.person.Person()

@person.onchristmas()
def christmas():
    print "It's Christmas"

类的实现如下所示:

# lib.person.py
class Person():

  def onchristmas(self):
    def decorator(f):
      self.christmas_handler = f
      return f
    return decorator

  def is_christmas(self):
    # called from somewhere else:
    self.christmas_handler()

问题是我不能在不构造person的情况下导入main.py。同样,我不能将构造函数移动为:

person = None

def init():

    person = lib.person.Person()
    return person

因为那样的话,这个人就不是典型的装饰工人了。正确的方法是什么

  1. 我仍然可以使用decorator让人们实现自己的christmas操作,而无需编辑lib.person.py
  2. 我可以用init()显式构造person,而不是在导入时进行。你知道吗

编辑评论中的更多详细信息:

事实上,有许多不同的事情可以发生,不仅仅是圣诞节,而且每个动作不只是一个处理程序,可能有一个数字,所有的处理程序都必须执行:

所以:

  def onchristmas(self):
    def decorator(f):
      self.christmas_handler.append(f)
      return f
    return decorator

  def is_christmas(self):
      # called from somewhere else:
      for h in self.christmas_handler:
          h()

用法:我希望其他人能够指定一个或多个操作的行为,而不必知道如何/何时调用它们,理想情况下,可以进一步取消注册处理程序。你知道吗

我还应该提到的是,只有Person的实例才会出现,不过我对Python中的静态方法和单例不太熟悉。谢谢你的帮助!你知道吗


Tags: 方法pyself处理程序returnmainlibdef
1条回答
网友
1楼 · 发布于 2024-06-03 13:48:45

问题是你的装饰者和你的州的混合。为什么不把decorator从类中分离出来,允许用户提供自己的函数呢。这样,装饰程序所依赖的唯一状态就是提供给它的状态。类似的东西:

def christmas_config(user_defined_func):
   def inner_config(func):
       def f(*args, **kwargs):
          print 'Hey Yo'
          return user_defined_func(func, *args, **kwargs)
       return f
   return inner_config

def test(func, *args, **kwargs):
   print 'This is hairy'
   return func(*args, **kwargs)

@christmas_config(test)
def my_func():
   print 'test'

my_func()

相关问题 更多 >