Python创建自定义魔术方法

时间:2018-10-31 14:00:13

标签: python customization magic-methods

在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 个答案:

答案 0 :(得分:0)

def logging(cls):
  return cls.__logging__()

class Cls:
  def __logging__(self):
    return "__logging__ called"

答案 1 :(得分:0)

` def记录(cls):   返回cls。记录()

Cls类:   def 记录(自己):     返回“称为__logging”

c = Cls() 打印(logging(c)) `