首页 > 解决方案 > Python 创建自定义魔术方法

问题描述

在 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'

标签: pythoncustomizationmagic-methods

解决方案


基本理念

在 python 中,所有默认的或内置的 dunder 方法都由特定函数调用。例如,__next__被调用next()__len__被调用len(),...等。所以当我们制作自定义dunder方法时,我建议您制作一个可以调用dunder方法的函数。

编码

# lets first make a function that will call a the logging method
# the function accepts an argument which is a class that is assumed to have a
# __logging__ method.


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

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

# you can use this method by this code

cls = Cls()
print(logging(cls))  # output => logging called

# or if you don't have a function to call the dunder method
# you can use this

cls = Cls()
print(cls.__logging__())  # output => logging called

推荐阅读