python - 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'
解决方案
基本理念
在 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
推荐阅读
- reactjs - React Calendly Package 无限加载
- android - 未验证 App Store ID 或 Google Play 包名称
- airflow - 添加了气流模板字段,但像 {{ ds }} 这样的变量不起作用
- python - Django 表单验证:显示输入有效日期,但给出的日期是正确的
- excel - 有条件地在工作表之间复制、粘贴、删除数据丢失
- security - 我们可以将加密的秘密(安全地)存储在环境变量中吗?
- javascript - 我如何导出一个 JavaScript 类
- pandas - 使用pandas库根据csv中的另一个列值填充空白值
- java - 无法解析 imageView 中的方法 setText()
- javascript - 由于 ./node_modules/vue-loader/lib/template-compiler 中的错误,模块构建失败