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?
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With