Jas*_*ca1 2 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'
Run Code Online (Sandbox Code Playgroud)
小智 8
在 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
Run Code Online (Sandbox Code Playgroud)