2017-06-27 28 views
2

Cythonを使って効率的にPythonコードをコンパイルしてより速くする方法を学習しています。Cython:.pydファイルをインポートするとエラーが返されます(init関数が不足しています)

  1. は私がmath_code_python.pyというPythonファイルを作成し、その中で4つの単純な関数を置く:ここ

    は、私がこれまで行ってきたものです。

  2. このファイルをmath_code_cython.pyxという名前で保存しました。
  3. setup.pyというセットアップファイルを作成しました。
  4. Command Promptpython C:\Users\loic\Documents\math_code\setup.py build_ext --inplaceと入力しました。
  5. math_code_cython.cp36-win_amd64.pydという名前のコンパイル済みファイルがあり、これをmath_code_pyd.pydという名前に変更しました。
  6. 最後に、だけを持つtest_math_code.pydと呼ばれるPythonファイルを作成しました。

:私はこのファイルを実行すると、私はそのメッセージが表示されました

私の質問は、どうすればいいですか?私はmath_code_python.pyの末尾に次のような関数を入れなければなりませんか?

def __init__(self): 
    # something ? 

のPythonの私のバージョン:

Python 3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)] 

math_code_python.py

def fact(n): 
    if n==0 or n==1: 
     return 1 
    else: 
     return n*fact(n-1) 

def fibo(n): 
    if n==0 or n==1: 
     return 1 
    else: 
     return fibo(n-1)+fibo(n-2) 

def dicho(f, a, b, eps): 
    assert f(a)*f(b) < 0 
    while b-a > eps: 
     M = (a+b)/2. 
     if f(a) * f(M) > 0: 
      a = M 
     else: 
      b = M 
    return M 

def newton(f, fp, x0, eps): 
    u = x0 
    v = u - f(u)/fp(u) 
    while abs(v-u) > eps: 
     u = v 
     v = u - f(u)/fp(u) 
    return v 

setup.py

try: 
    from setuptools import setup 
except ImportError: 
    from distutils.core import setup 

from Cython.Distutils import build_ext 
from Cython.Build import cythonize 

import numpy as np 

setup(name = "maido", 
     include_dirs = [np.get_include()], 
     cmdclass = {'build_ext': build_ext}, 
     ext_modules = cythonize(r"C:\Users\loic\Documents\math_code\math_code_cython.pyx"), 
    ) 

答えて

1

あなたのマイルステークはpydファイルの名前を変更しています。 import math_code_pydに電話すると、具体的にはinitmath_code_pyd(Python2)またはPyInit_math_code_pyd(Python3)が検索されます。

Cythonでコンパイルすると、.pyxファイル名(つまりinitmath_code_cythonまたはPyInit_math_code_cython)に一致する関数が生成されます。したがって、それは期待する機能を見つけることができません。 この関数を自分で用意する必要はありません。Cythonが生成します。

名前を.pyxファイルに付けて、モジュールを呼び出す場所を指定し、.pydファイルの名前を変更しないでください。 (原則として、.cp36-win_amd64は削除できますが、それは理由があり便利です)。

関連する問題