gpt4 book ai didi

Python 创建自定义魔术方法

转载 作者:太空宇宙 更新时间:2023-11-03 21:38:31 25 4
gpt4 key购买 nike

在 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

关于Python 创建自定义魔术方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53085202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com