[英]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 的等效约束是什么?
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 中,这是float
的int
实例。 As bool
is a subclass of int
, it is included.由于bool
是int
的子类,因此它被包括在内。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.