简体   繁体   English

如何将 JavaScript('对象')翻译成 Python?

[英]How to translate JavaScript ('object') into Python?

I am working on converting some JavaScript code into Python.我正在将一些 JavaScript 代码转换为 Python。

There is an if condition in the JavaScript that looks something like: if (typeof f === 'object') and then a series of actions are taken if this condition evaluates to true. JavaScript 中有一个 if 条件,类似于: if (typeof f === 'object') ,如果此条件评估为真,则执行一系列操作。

In this case f would be something like: f = { 'fields': ["user_id", "date_started", "date_ended"] }在这种情况下, f将类似于: f = { 'fields': ["user_id", "date_started", "date_ended"] }

In this case f is a dict , but it might not always be the case.在这种情况下, f是一个dict ,但可能并非总是如此。

I know that in JavaScript nearly everything is considered an object.我知道在 JavaScript 中,几乎所有东西都被认为是 object。 What would be the equivalent constraint to object in Python? object中 object 的等效约束是什么?

you can use type method for getting type of variables in python:您可以使用type方法获取 python 中的变量类型:

if (type(f) is dict)

Actually, js objects in python are dictionaries!其实python中的js对象就是字典! you can see more details from this link .您可以从此链接查看更多详细信息。

In JavaScript typeof f == 'object' is true when all of the following is not true:在 JavaScript typeof f == 'object'中,当以下所有条件都不为真时为真:

  • f is undefined : there is no equivalent in Python f undefined :Python 中没有等效项
  • f is a boolean, number or bigint: in Python this is an instance of int of float . f是 boolean,数字或 bigint:在 Python 中,这是floatint实例。 As bool is a subclass of int , it is included.由于boolint的子类,因此它被包括在内。
  • f is a string: in Python this is an instance of str f是一个字符串:在 Python 这是str的一个实例
  • f is symbol: there is no equivalent in Python f是符号:Python 中没有等价物
  • f is a function: in Python you can use callable to detect this f是 function:在 Python 中,您可以使用callable来检测它

Caveat: typeof null == 'object' is true, so in Python None should pass the equivalent test.警告: typeof null == 'object'为真,所以在 Python 中None应该通过等效测试。

So this brings us to the following test in Python:所以这将我们带到 Python 中的以下测试:

if not (callable(f) or isinstance(f, (int, float, str))):
    # it is an "object"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM