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'
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Jasonca1
  • 4,848
  • 6
  • 25
  • 42
  • Check out this post: https://stackoverflow.com/questions/2654113/how-to-get-the-callers-method-name-in-the-called-method – charley Oct 31 '18 at 14:08

1 Answers1

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
basic mojo
  • 128
  • 2
  • 12
Fouad Grimate
  • 81
  • 1
  • 3