代码之家  ›  专栏  ›  技术社区  ›  Jasonca1

python创建自定义魔术方法

  •  0
  • Jasonca1  · 技术社区  · 6 年前

    在python中,如果我想创建一个对象,它在传递给特定函数时做了一些事情,我该怎么做呢? 例如:

    import logging
    class  TestObject:
        def __logging__(self):
            # It would check the calling function here and return something 
            # if it was a log function call from a logging class log function call
            return 'Some text'
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   Patrick Haugh    6 年前
    def logging(cls):
      return cls.__logging__()
    
    class Cls:
      def __logging__(self):
        return "__logging__ called"
    
        2
  •  0
  •   Fouad Grimate    6 年前

    ` 定义日志(CLS): 返回CLS。 登录中 ()

    CLS类: DEF 登录中 (自我): return“调用了日志记录”

    c = 打印(日志(c)) `