2

In python, if I wanted to create an object that did something when passed to a specific function, how could I do that? For example:

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

1 Answer 1

8

Basic Idea

In python all the default, or inbuild dunder methods are called by specific function. For example, the __next__ is called by next(), __len__ is called by len(), ... etc. So when we make a custom dunder method I suggest you to make a function that can call the dunder method.

The code

# 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
Sign up to request clarification or add additional context in comments.

1 Comment

Please include an explanation of your code. Code-only answers are generally frowned upon on SO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.