73

I read on another Stack Overflow question that Python was just like Ruby, as it relates to "everything's an object," and everything in Python was an object, just like Ruby.

Is this true? Is everything an object in Python like Ruby?

How are the two different in this respect or are they really the same? For example, can you take a number and do the Ruby stuff I've seen like:

y = 5.plus 6

Can that be done the same way in Python?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
johnny
  • 19,272
  • 52
  • 157
  • 259
  • When you say "object" do you mean exactly the OOP terminology? Both python and ruby are rather newbie languages, so you question make more sense to me if you would actually ask it related to Smalltalk, C++ or to OOP-paradigm (theory) abstracted from any particular language: "Is python a pure OO language, i.e. every (data) type is an object (or a class of objects)?" http://en.wikipedia.org/wiki/Object-oriented_programming – Yauhen Yakimovich Sep 11 '12 at 23:51
  • **See also:** https://stackoverflow.com/questions/192649/can-you-monkey-patch-methods-on-core-types-in-python – dreftymac Apr 12 '19 at 16:56
  • Not "everything" is an object in Ruby. Every (reasonable) value is an object (that is, there are no primitives, even `nil` is an object), but beyond that it gets more tricky. Classes are objects, methods are not. Procs are objects, blocks are not. (but both a method and a block can be converted into and from a Proc). Bindings are objects, local variables are not. Etc... – Pelle Jun 13 '23 at 10:20

8 Answers8

96

DiveIntoPython - Everything Is an Object

Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the doc string defined in the function's source code. The sys module is an object which has (among other things) an attribute called path. And so forth.

Still, this begs the question. What is an object? Different programming languages define “object” in different ways. In some, it means that all objects must have attributes and methods; in others, it means that all objects are subclassable. In Python, the definition is looser; some objects have neither attributes nor methods (more on this in Chapter 3), and not all objects are subclassable (more on this in Chapter 5). But everything is an object in the sense that it can be assigned to a variable or passed as an argument to a function (more in this in Chapter 4).

Ruby Docs - To Ruby From Python

As with Python, in Ruby,... Everything is an object

So there you have it from Ruby's own website: in Python everything is an object.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Unknown
  • 45,913
  • 27
  • 138
  • 182
  • 2
    +1 well put. As a Rubyist, I tend towards the "objects must have methods" side of the argument, but the "everything can be passed as an argument" argument is well put (and I suspect better reflects the Pythonista viewpoint) – rampion May 15 '09 at 00:04
  • 29
    "But everything is an object in the sense that it can be assigned to a variable or passed as an argument to a function (more in this in Chapter 4)." That doesn't make any sense to me. Wouldn't that make Java int objects? – James McMahon May 21 '09 at 19:58
  • 8
    @JamesMcMahon Yes, you are right!! Above answer did not answer the question!! If we read Guido's [blog](http://python-history.blogspot.in/2009/02/first-class-everything.html), it says: `One of my goals for Python was to make it so that all objects were "first class." By this, I meant that I wanted all objects that could be named in the language (e.g., integers, strings, functions, classes, modules, methods, etc.) to have equal status. That is, they can be assigned to variables, placed in lists, stored in dictionaries, passed as arguments, and so forth.` – overexchange Feb 24 '15 at 08:22
  • 2
    I might also say: "objects in the sense that they are implemented with the same inherent structures/places for hooks in CPython as other objects"... – Owen S. Aug 03 '15 at 20:32
  • 1
    I think the common understanding is that an object is a container for methods and fields where access to those internal methods and fields is controlled by the object itself. That means, to get to execute the methods or read/write from the fields, you must ask the object to do for you. I don't know python, but it looks like it might not fit that definition. I think you could make a language where absolutely everything at run-time is like that, and all objects would be contained in a master object, so even reference equality could be a method of the master object. – Didier A. Jan 30 '16 at 03:23
  • 1
    In Python everything is a name, not an object. Since names, unlike variables, do not own the memory of the thing they represent, they cannot be said to be that thing (i.e. object). Objects in Python exist independently of the names that reference it, so they are not the same thing. Shakespeare didn't write King Lear, it was written by a man called Shakespeare. Shakespeare is not a man, it is a name of a man. In the same way, `x` is not an object, it is a name (possibly one of many) of an object. – Confounded Nov 25 '20 at 11:16
  • No, within Python 3.8.5 for example Delimiters, Operators and Keywords are not objects. https://stackoverflow.com/a/66374328/11554034 – Francisco Costa Feb 27 '21 at 10:35
45

While everything is an object in Python, it differs from Ruby in its approach to resolving names and interacting with objects.

For example, while Ruby provides you with a 'to_s' method on the Object base class, in order to expose that functionality, Python integrates it into the string type itself - you convert a type to a string by constructing a string from it. Instead of 5.to_s, you have str(5).

Don't be fooled, though. There's still a method behind the scenes - which is why this code works:

(5).__str__()

So in practice, the two are fundamentally similar, but you use them differently. Length for sequences like lists and tuples in Python is another example of this principle at work - the actual feature is built upon methods with special names, but exposed through a simpler, easier-to-use interface (the len function).

The Python equivalent to what you wrote in your question would thus be:

(5).__add__(6)

The other difference that's important is how global functions are implemented. In Python, globals are represented by a dictionary (as are locals). This means that the following:

foo(5)

Is equivalent to this in Python:

globals()["foo"].__call__(5)

While Ruby effectively does this:

Object.foo(5)

This has a large impact on the approach used when writing code in both languages. Ruby libraries tend to grow through the addition of methods to existing types like Object, while Python libraries tend to grow through the addition of global functions to a given module.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Katelyn Gadd
  • 1,383
  • 9
  • 13
  • "Python libraries tend to grow through the addition of global functions to a given module." This is not really correct. globals()["foo"] returns an object. The __call__ is a method, not a global function. You can't do globals()["__call__"] – Unknown May 18 '09 at 07:04
  • My point was that foo is not a method of the module. It's an attribute of the module, which happens to be callable, and importing it also adds it to globals(). __call__ is a method, yes. In Ruby, foo is a method of Object, in comparison. – Katelyn Gadd May 18 '09 at 17:22
  • 2
    I was trying to understand why can I do "1".__eq__("2") => False, but not 1.__eq__(2) => SyntaxError: invalid syntax. Your answer shows that I need parentheses, e.g., (1).__eq__(2). Strangely, @RichieHindle's 1..__add__(2) works, but not with a single period. Why is this? – Matthew Cornell Sep 04 '12 at 19:38
  • 1
    @MatthewCornell I think because in case of 1.__add__(5) after decimal interpreter was expecting some numeral but found _ which is not a numeral hence it raises error, however in case of 1..__add__(5), second decimal can not serve any purpose except calling some attribute or method. – chandola Jan 15 '17 at 09:52
25

"everything" is a tad of an overbid, for both Python and Ruby -- for example, if is not "an object", rather it's a keyword used to start a conditional statement or (in Python) inside list comprehensions and generator expressions. The enthusiasm of finding out that functions, classes, methods, and all sort of such things that aren't really objects in (say) C++, are objects in Ruby or Python, causes such enthusiasm. Other things may be objects in Ruby but not Python or viceversa (code blocks, regular expressions, ...).

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 5
    Yes, but even on smalltalk, where 'if' is a method of block (Proc/lambda on ruby, lambdas on python, closures for language-agnostic guys), and everything is an object, has its keywords true, false, nil, self, super and thisContext. Sure enough, those are more like pseudo-variables... – Daniel Ribeiro Jan 29 '10 at 23:22
  • While the example in this answer is correct, there are less obvious things in Ruby that aren't objects. Most notoriously: **blocks** and **methods** are themselves _NOT_ objects in Ruby. Both can be converted to and from a Proc, which _IS_ an object, using `proc`, `&`, `&:` and `define_method`. – Pelle Jun 13 '23 at 10:14
23

In answer to your second question, yes:

>>> (1).__add__(2)
3
RichieHindle
  • 272,464
  • 47
  • 358
  • 399
2

Yep, as far as I know everything is an object in Python. Certainly the primitive and builtin types (int, long, str, float, etc.) can be subclassed - and in fact the types themselves are objects. Functions are objects, classes are objects, even code blocks are objects in a sense... I can't think of anything in Python that can't be treated as an object.

David Z
  • 128,184
  • 27
  • 255
  • 279
  • is a `# comment` an object? This isn't a criticism; I'm honestly curious. –  Feb 09 '18 at 20:30
  • 1
    @ocertat No, at least not in the sense I think you mean. Comments are a feature of the source code, but not of the program itself. When the Python parser runs, it simply discards any text in a comment and doesn't act on it. (However, there is a Python source code parser in the standard library, and if you run that on a source file with comments, it may produce objects that correspond to those comments - I don't remember offhand if it does that.) – David Z Feb 09 '18 at 21:20
  • 1
    I don't think `if` is an object. – Brian Spiering Jul 25 '19 at 03:24
1

Hello and answer is out of the bat not everything, reference is more complete than that and offers many more avenues, within Python 3.8.5 for example Delimiters, Operators and Keywords are not objects. stackoverflow.com/a/66374328/11554034

Have explained it with some detail in that link feel free to check it along.

Anyway, next one says that statement you can correct it by saying (something more correct, although if still can be more completed feel free): "Everything in a logical line that is not NEWLINE, INDENT, DEDENT, Space bar Character, Operator, Keyword or Delimiter is an object in Python."

Cheers.

1

To add a comment to other people's excellent answers: everything is an object, but some – notably strings and numeric types – are immutable. This means that these types behave the way they do in languages like C or Java (where integers, etc. are not objects) with respect to assignment, parameter passing, etc, and you never have to worry about traps caused by pass-by-reference. It's rather a good solution :-)

John Fouhy
  • 41,203
  • 19
  • 62
  • 77
0

Yes, everything is object in Python as long as I researched.

The documentation says below:

Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects.

Every object has an identity, a type and a value.

And, I also checked the type of each value and if each of them is the instance of a particular class as shown below:

from types import FunctionType

class Person:
    pass

def test():
    pass

print(type("Hello"), isinstance("Hello", str))
print(type(100), isinstance(100, int))
print(type(100.23), isinstance(100.23, float))
print(type(100 + 2j), isinstance(100 + 2j, complex))
print(type(True), isinstance(True, bool))
print(type(None), isinstance(None, type(None)))
print(type([]), isinstance([], list))
print(type(()), isinstance((), tuple))
print(type({}), isinstance({}, dict))
print(type({""}), isinstance({""}, set))
print(type(Person), isinstance(Person, type))
print(type(test), isinstance(test, FunctionType))

Output:

<class 'str'> True
<class 'int'> True
<class 'float'> True
<class 'complex'> True
<class 'bool'> True
<class 'NoneType'> True
<class 'list'> True
<class 'tuple'> True
<class 'dict'> True
<class 'set'> True
<class 'type'> True
<class 'function'> True
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129