What is type conversion in Python?

AFAIK types and classes are different things.

Not in Python.

A callable class implements the __call__ method, and its instantiated object can be called like a function.
In my understanding, float is a type, but not a class. So I’m curious
whether it is callable or not.

Reference:
python - What is a "callable"? - Stack Overflow

Hahaha! The problem with stackoverflow and its friends is that they are
filled with misinformation and bad advice. Also good infrmation and good
advice, but they’re basicly hearsay. If you hear from someone with
incorrect ideas, you hear incorrect information. Or vague information.

All classes are callable, because that is what you do to instantiate a
new object:

x = int(9)      # an int from an int
x = int("9")    # an int from a string
x = int(9.0)    # an int from a float

You’re conflating call with a “callable class”. What call does
is make the instances callable.

So, an int such as 9 or a float such as 9.0 is not callable.

But if I make class with a call method:

class C:

    def __init__(self, name):
        self.name = name

    def __call__(self, something):
        return "Hello " + self.name + ", here is a " + something + "."

Then:

c = C("Ssuching Yu")

That makes an instance of “C” with the name “Ssuching Yu”. We did that
by calling the class. That returns an instance.

Because there is a call method, we can call “c”:

result = c("piece of example code")

Now the variable result should contain:

"Hello Ssuching Yu, here is a piece of example code."

By contrast, an int is not callable. First, call the int class to make
an int:

x = int("9")

but we cannot call the instance:

x()

because the class has no call method. In full at the Python prompt:

>>> x = int("9")
>>> x
9
>>> x()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like