Red Char
Red Char

Reputation: 157

what exactly are built-in types in Python?

I keep hearing "everything is an object" in both Ruby and Python world. Well, what are built-in functions then? Can someone explain that in layperson English? For example:

file=open(abc.txt)

open is a built-in function. Is it an object? Is it a method? Of what class?

How did we even end-up with functions in Python if everything is an object? I mean, shouldn't we be having class, objects, methods and attributes, instead of functions? I thought we had functions in languages like C. Python, Ruby and Java had classes, objects, attributes, methods.

In Ruby (irb), you could do something like 1.class and this will give you Fixnumit will show you which class it belongs to. I don't seem to be able to do this in Python shell. Is there an equivalent?

FYI:

Upvotes: 2

Views: 255

Answers (2)

Eduardo Ivanec
Eduardo Ivanec

Reputation: 11852

Everything is an object, but not every object is an instance of a useful class in the classic sense. Some things you're better off treating as plain objects, as far as I can tell (functions are a good example that's already been given).

Note that you can use type(obj) or inspect obj.__class__ to replicate Ruby's .class method somewhat (see delnan's comment about the caveat for integers, though). You can also see the 'order' of the full inheritance sequence by issuing type.mro(type(obj)).

In [7]: type.mro(type(open))
Out[7]: [<type 'builtin_function_or_method'>, <type 'object'>]

In [4]: import datetime
In [5]: d = datetime.datetime(2009,11,11)
In [6]: type.mro(type(d))
Out[6]: [<type 'datetime.datetime'>, <type 'datetime.date'>, <type 'object'>]

Upvotes: 0

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29975

They are all listed here: http://docs.python.org/library/functions.html

The function open is an object (all functions are objects) and belongs to the __builtin__ module. They are simply built-in, and available to all objects, since they are automatically imported (something like from __builtin__ import *).

>>> print repr(open)
<built-in function open>

>>> print open.__module__
__builtin__

>>> import __builtin__
>>> print __builtin__.open
<built-in function open>

Update
You mentioned in your edit that you don't know what assigning a function means.

>>> o = open
>>> print repr(open)
<built-in function open>
>>> print repr(o)
<built-in function open>
>>> o('file.txt')
<open file 'file.txt', mode 'r' at 0x107fe49c0>

Upvotes: 3

Related Questions