Wednesday 6 December 2017

Python type() function returns a callable

Let's run through some
examples:



/>


>>>
type(int)
'type'>


So, since
type(int) returns a type, it makes
sense that



>>>
type(int)(12)
'int'>



since



>>>
type(12)
'int'>


More
importantly:



>>>
(type(int)(12) == type(12)) and (type(int)(12) is
type(12))
True



/>

Now, if you instead
do:



>>>
type(int())
'int'>



which
is also expected
since



>>> (int() == 0)
and (int() is
0)
True


and



>>>
(type(int()) = type(0)) and (type(int()) is
type(0))
True



/>

So, putting things together:




  • int
    is an object of type
    type

  • int()
    is an (integer) object of type
    int




/>

Another
example:



>>>
type(str())
'str'>


which means
that




>>>
(type(str())() == '') and (type(str())() is
'')
True


therefore,
it behaves just like a string
object:



>>>
type(str())().join(['Hello', ', World!'])
'Hello,
World!'



/>

I have the feeling that I might have made this seem
much more complicated than it actually is... it
isn't!



/>

type() returns the class of
an object.
So:





  • type(12)
    is just an ugly way of writing
    int

  • type(12)(12)
    is just an ugly way of writing
    int(12)



So,
"Yes!", type() returns a callable. But it's much better to
think about it as (from href="https://docs.python.org/3/library/functions.html#type" rel="nofollow
noreferrer">official docs )



readability="7">

class
type(object)




With one argument, return the type of an object. The return value is a type
object and generally the same object as returned by
object.__class__.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...