我如何使用 PyCall 在 julia 中使用 python 内置函数,如 isinstance()
How can i use python built-in function like isinstance() in julia using PyCall
PyCall 文档说:
重要提示:与 Python 的最大区别在于对象 attributes/members 是使用 o[:attribute] 而不是 o.attribute 访问的,因此 o.method(...) in Python 在 Julia 中被 o:method 取代。此外,您使用 get(o, key) 而不是 o[key]。 (但是,您可以像在 Python 中那样通过 o[i] 访问整数索引,尽管使用基于 1 的 Julian 索引而不是基于 0 的 Python 索引。)
但我不知道要导入哪个模块或对象
这是一个让您入门的简单示例
using PyCall
@pyimport numpy as np # 'np' becomes a julia module
a = np.array([[1, 2], [3, 4]]) # access objects directly under a module
# (in this case the 'array' function)
# using a dot operator directly on the module
#> 2×2 Array{Int64,2}:
#> 1 2
#> 3 4
a = PyObject(a) # dear Julia, we appreciate the automatic
# convertion back to a julia native type,
# but let's get 'a' back in PyObject form
# here so we can use one of its methods:
#> PyObject array([[1, 2],
#> [3, 4]])
b = a[:mean](axis=1) # 'a' here is a python Object (not a python
# module), so the way to access a method
# or object that belongs to it is via the
# pythonobject[:method] syntax.
# Here we're calling the 'mean' function,
# with the appropriate keyword argument
#> 2-element Array{Float64,1}:
#> 1.5
#> 3.5
pybuiltin(:type)(b) # Use 'pybuiltin' to use built-in python
# commands (i.e. commands that are not
# under a module)
#> PyObject <type 'numpy.ndarray'>
pybuiltin(:isinstance)(b, np.ndarray)
#> true
PyCall 文档说: 重要提示:与 Python 的最大区别在于对象 attributes/members 是使用 o[:attribute] 而不是 o.attribute 访问的,因此 o.method(...) in Python 在 Julia 中被 o:method 取代。此外,您使用 get(o, key) 而不是 o[key]。 (但是,您可以像在 Python 中那样通过 o[i] 访问整数索引,尽管使用基于 1 的 Julian 索引而不是基于 0 的 Python 索引。)
但我不知道要导入哪个模块或对象
这是一个让您入门的简单示例
using PyCall
@pyimport numpy as np # 'np' becomes a julia module
a = np.array([[1, 2], [3, 4]]) # access objects directly under a module
# (in this case the 'array' function)
# using a dot operator directly on the module
#> 2×2 Array{Int64,2}:
#> 1 2
#> 3 4
a = PyObject(a) # dear Julia, we appreciate the automatic
# convertion back to a julia native type,
# but let's get 'a' back in PyObject form
# here so we can use one of its methods:
#> PyObject array([[1, 2],
#> [3, 4]])
b = a[:mean](axis=1) # 'a' here is a python Object (not a python
# module), so the way to access a method
# or object that belongs to it is via the
# pythonobject[:method] syntax.
# Here we're calling the 'mean' function,
# with the appropriate keyword argument
#> 2-element Array{Float64,1}:
#> 1.5
#> 3.5
pybuiltin(:type)(b) # Use 'pybuiltin' to use built-in python
# commands (i.e. commands that are not
# under a module)
#> PyObject <type 'numpy.ndarray'>
pybuiltin(:isinstance)(b, np.ndarray)
#> true