如何使用PyCall

时间:2017-08-06 15:49:51

标签: python julia built-in

PyCall文件说: 重要:与Python最大的区别在于,使用o [:attribute]而不是o.attribute访问对象属性/成员,因此Python中的o.method(...)将被Julia中的o:方法替换。此外,您使用get(o,key)而不是o [key]。 (但是,您可以通过o [i]访问整数索引,就像在Python中一样,虽然使用基于1的Julian索引而不是基于0的Python索引。)

但我不知道要导入哪个模块或对象

1 个答案:

答案 0 :(得分:3)

这是一个让你入门的简单例子

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