2

is it possible to create a python object that has the following property:

class Foo:
  def __default_method__(x):
      return x

f = Foo()
f(10)
> 10

That is to say, an object that when instantiated allows for a method to be called without the need for an explicit method name?

2
  • This is called a functor. Commented Jun 9, 2015 at 23:21
  • In Python, we usually don't use the term "functor," because in Python, functions are first class, so the functor pattern is a solution in search of a problem. Instead, we speak of whether an object is callable. Commented Jun 10, 2015 at 1:28

2 Answers 2

7

Yes. It's called __call__().

Sign up to request clarification or add additional context in comments.

Comments

3

As Kevin pointed out in his answer, __call__ is what you are looking for.

As a matter of fact, every time you create a class object you are using a callable class (the class's metaclass) without realizing it.

Usually we make a class this way:

class C(object):
    a = 1

But you can also make a class this way:

C = type('C',(object,),{'a':1})

The type class is the metaclass of all Python classes. The class C is an instance of type. So now, when you instantiate an object of type C using C(), you are actually calling the type class.

You can see this in action by replacing type with your own metaclass:

class MyMeta(type):
    def __call__(self):
        print("MyMeta has been called!")
        super().__call__()

class C(object, metaclass = MyMeta):
    pass

c = C() # C() is a CALL to the class of C, which is MyMeta
> My Meta has been called!

Comments

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.