Python default/unnamed method

334 Views Asked by At

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

There are 2 best solutions below

0
On BEST ANSWER

Yes. It's called __call__().

0
On

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!