Python 中的所有东西都像 Ruby 一样都是对象吗?

发布于 2024-07-19 21:26:55 字数 272 浏览 4 评论 0原文

我在另一个 Stack Overflow 问题上读到,Python 就像 Ruby,因为它与“一切都是对象”有关,而 Python 中的一切都是对象,就像 Ruby 一样。

这是真的? Python 中的所有东西都像 Ruby 一样都是对象吗?

两者在这方面有何不同或实际上相同? 例如,您可以获取一个数字并执行我见过的 Ruby 操作,例如:

y = 5.plus 6

可以在 Python 中以同样的方式执行此操作吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

温柔女人霸气范 2024-07-26 21:26:57

对于 Python 和 Ruby 来说,“everything” 有点过高——例如,if 不是“对象”,而是用于启动条件语句的关键字或(在 Python 中)内部列表推导式和生成器表达式。 发现函数、类、方法和所有类似的东西在(比如)C++ 中并不是真正的对象,而在 Ruby 或 Python 中却是对象,这种热情引起了人们的热情。 其他东西可能是 Ruby 中的对象,但不是 Python 中的对象,反之亦然(代码块、正则表达式……)。

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

望笑 2024-07-26 21:26:57

虽然 Python 中的一切都是对象,但它在解析名称和与对象交互的方法上与 Ruby 不同。

例如,虽然 Ruby 在 Object 基类上提供了“to_s”方法,但为了公开该功能,Python 将其集成到字符串类型本身中 - 您可以通过从类型构造字符串来将类型转换为字符串。 您使用的是 str(5),而不是 5.to_s

不过,别被愚弄了。 幕后仍然有一个方法 - 这就是这段代码起作用的原因:

(5).__str__()

因此在实践中,两者基本相似,但使用方式不同。 Python 中列表和元组等序列的长度是此原理在工作中的另一个示例 - 实际功能是基于 具有特殊名称的方法,但通过更简单、更易于使用的接口(len 函数)公开。

因此,与您在问题中所写内容等效的 Python 是:

(5).__add__(6)

另一个重要的区别是全局函数的实现方式。 在 Python 中,全局变量由字典表示(局部变量也是如此)。 这意味着以下内容:

foo(5)

与 Python 中的等效:

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

而 Ruby 有效地做到了这一点:

Object.foo(5)

这对用两种语言编写代码时使用的方法有很大影响。 Ruby 库倾向于通过向 Object 等现有类型添加方法来实现增长,而 Python 库则倾向于通过向给定模块添加全局函数来实现增长。

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.

另类 2024-07-26 21:26:57

对其他人的优秀答案添加评论:一切都是对象,但有些(尤其是字符串和数字类型)是不可变的。 这意味着这些类型在赋值、参数传递等方面的行为方式与 C 或 Java 等语言(其中整数等不是对象)的行为方式相同,并且您永远不必担心由 pass-by- 引起的陷阱参考。 这是一个很好的解决方案:-)

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 :-)

<逆流佳人身旁 2024-07-26 21:26:57

是的,只要我研究过,Python中的一切都是对象。

文档 如下:

对象是 Python 对数据的抽象。 所有数据都在Python中
程序由对象或对象之间的关系来表示。

每个对象都有一个身份、类型和值。

而且,我还检查了每个值的类型,以及它们是否都是特定类的实例,如下所示:

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))

输出:

<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

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
昇り龍 2024-07-26 21:26:57

你好,答案并不是全部,参考比这更完整,并提供了更多途径,例如在 Python 3.8.5 中,分隔符、运算符和关键字不是对象。 stackoverflow.com/a/66374328/11554034

已在该链接中详细解释了它,请随时查看。

无论如何,下一个说的是这个陈述,你可以通过说来纠正它(更正确的东西,尽管如果仍然可以更完整,请随意):
“逻辑行中除 NEWLINE、INDENT、DEDENT、空格键字符、运算符、关键字或分隔符之外的所有内容都是 Python 中的对象。”

干杯。

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.

栖竹 2024-07-26 21:26:57

是的,据我所知,Python 中一切都是对象。 当然,原始类型和内置类型(int、long、str、float 等)可以被子类化 - 事实上,类型本身就是对象。 函数是对象,类是对象,甚至代码块在某种意义上也是对象......我想不出Python中有任何东西不能被视为对象。

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.

So要识趣 2024-07-26 21:26:57

回答你的第二个问题,是的:

>>> (1).__add__(2)
3

In answer to your second question, yes:

>>> (1).__add__(2)
3
£烟消云散 2024-07-26 21:26:56

DiveIntoPython - 一切都是对象

Python 中的一切都是对象,几乎一切都有属性和方法。 所有函数都有一个内置属性__doc__,它返回函数源代码中定义的doc stringsys 模块是一个对象,它具有(除其他外)名为 path 的属性。 等等。

不过,这还是引出了一个问题。 什么是对象? 不同的编程语言以不同的方式定义“对象”。 在某些情况下,这意味着所有对象必须具有属性和方法; 在其他情况下,这意味着所有对象都是可子类化的。 在Python中,定义比较宽松; 有些对象既没有属性也没有方法(第 3 章将详细介绍),而且并非所有对象都是可子类化的(第 5 章将详细介绍)。 但一切都是对象,因为它可以被分配给变量或作为参数传递给函数(更多内容将在第 4 章中介绍)。

Ruby 文档 - 到 Ruby From Python

与 Python 一样,在 Ruby 中,...一切都是对象

因此,您可以从 Ruby 自己的网站上找到它:在 Python 中,一切都是对象。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文