Is everything an object in Python like Ruby?
Asked Answered
A

8

76

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?

Absorbent answered 14/5, 2009 at 21:33 Comment(3)
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)?" en.wikipedia.org/wiki/Object-oriented_programmingArianna
See also: #193149Charmer
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...Exercise
T
98

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.

Trass answered 14/5, 2009 at 21:40 Comment(7)
+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)Rebecarebecca
"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?Tennant
@JamesMcMahon Yes, you are right!! Above answer did not answer the question!! If we read Guido's blog, 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.Charlinecharlock
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"...Interstellar
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.Woodcut
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.Furcate
No, within Python 3.8.5 for example Delimiters, Operators and Keywords are not objects. https://mcmap.net/q/37458/-everything-in-python-is-an-object-why-operators-are-notCampanulaceous
S
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.

Shadwell answered 14/5, 2009 at 22:3 Comment(4)
"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"]Trass
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.Shadwell
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?Boeotian
@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.Split
Q
26

"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, ...).

Quarterly answered 14/5, 2009 at 22:2 Comment(2)
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...Heartbreaker
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.Exercise
B
23

In answer to your second question, yes:

>>> (1).__add__(2)
3
Beatnik answered 14/5, 2009 at 21:51 Comment(3)
Yep. Or even 1. __add__(2) (note the space). Will even work for floats: 1..__add__(2).Disavow
@dF: Your first example, which uses a space after "1.", doesn't work for me in 3.2.3 => SyntaxError: invalid syntaxBoeotian
the space is supposed to be between the 1 and the dot :D 1 .__add__(2)Rosyrot
C
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.

Clubman answered 14/5, 2009 at 21:40 Comment(3)
is a # comment an object? This isn't a criticism; I'm honestly curious.Tolly
@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.)Clubman
I don't think if is an object.Hardened
C
2

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. https://mcmap.net/q/37458/-everything-in-python-is-an-object-why-operators-are-not

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.

Campanulaceous answered 27/2, 2021 at 10:37 Comment(0)
N
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 :-)

Nappe answered 14/5, 2009 at 23:8 Comment(0)
C
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
Cotquean answered 16/11, 2022 at 0:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.