Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "everything" in Python (3) an instance of some class?

I am new to Python but have already read a number of times the principle that everything in Python is an object.

Does that mean that everything is an instance of some class?

As an example, suppose we have a function f. Please then consider running the following.

def f(x):
    return x

print(type(f))

I get <class 'function'>. Does that mean somewhere there is a class called function of which f is an instance? Is it then possible to create a function using g = function(some argument here) as if I had defined the class function myself?

like image 794
Cabbage Avatar asked Sep 17 '25 13:09

Cabbage


1 Answers

You can create a function instance by using the def keyword.
It is a subclass of some generic class function. You can compare it to some virtual class which requires to implement the __call__ method.
Using the __call__ method you can use any object as a function:

class Hello:
    def __call__(self, name):
        print(f'Hello {name}')

h = Hello()
print(h('Cabbage')) # -> 'Hello Cabbage'
like image 130
Gil Ben David Avatar answered Sep 19 '25 02:09

Gil Ben David