Cython #2

by 03:36 0 comments
Cython ဒုတိယပိုင္းဆက္ရေအာင္ဗ်ာ ပထမပိုင္းတုံးကကြ်န္ေတာ္တို့ Hello World Program ေလးပဲေရးျဖစ္ခဲ့ပါတယ္ ေနာက္ Cython code ဘလို compile လုပ္မယ္ run မယ္ဆိုတာေျပာျပခဲ့ပါတယ္။
ဒီတစ္ေခါက္ေတာ့ Cython ရဲ့ classes အေျကာင္းတြေနာက္ function ဘလိုေရးမယ္ေနာက္ function declare လုပ္နည္း Cython မွာဘယ္နွမ်ိုးရိွတယ္ ဘယ္လိုကြာျခားတယ္ဆိုတာ ေျပာျပပါမယ္။

Class and function declaration in Cython

Object Oriented Programming ကို support လုပ္နိုင္ဖို့အတြက္ Cython ကလည္း Python ရဲ့ class ေရးသားနည္းကို support လုပ္ေပးထားပါတယ္။
 class function1():  
    def __init__(self, x):  
      self.x = x  
      self.output(x)  
    def output(self, x):  
      return x  
ဒါေပမယ့္ Cython မွာလဲသူ့ ကိုယ္ပိုင္ class တည္ေဆာက္တဲ့ keyword ရွိပါတယ္။
အဲ့တာကေတာ့ cdef classes ပါ။
ဒီေတာ့ cdef နဲ့ေရးတဲ့ class နဲ့ Python ရဲ့နကို class နဲ့ဘာကြာသလဲဆို...
cdef က memory အတြက္ efficient လဲပိုျဖစ္သလို, ပိုလဲျမန္ပါတယ္။
ဘာေျကာင့္လဲဆို Python ရဲ့ dict အစား C struct ကိုအသံုးျပုျပီး field, methods ေတြကိုသိမ္းဆည္းပါတယ္။ အဲ့ေတာ့ဘာထူးျခားသြားသလဲဆို arbitrary C types ေတြကို Python wrapper မပါပဲသိမ္းဆည္းနိုင္ပါတယ္။
Access လုပ္တဲ့အခါက်လဲ Field နဲ့ method ေတြကို Python dictionary lookup ကိုျခားခံမသံုးပဲ direct ဆက္သြယ္နိုင္ပါတယ္။
Python normal class ေတြက cdef ကို inheritance ျပုလုပ္နိုင္ေပမယ့္ cdef ကေနေတာ့ normal class ကိုေျပာင္းျပန္ျပန္လို့မရပါဘူး။  cdef နဲ့ class ေရးမယ္ဆိုရင္ေတာ့ေအာက္ကလိုပါ။

 cdef class <class_name>:  

cdef အျပင္ cpdef ဆိုတာလဲရွိပါေသးတယ္ ဘာကြာလဲဆိုတာကြ်န္ေတာ္ေျပာျပပါမယ္။
def, cdef, cpdef ၃ခုမွာဆို
cdef ကအျမန္ဆံုးပါ။ cdef function ကို ဒါေပမယ့္ Cython ကေနပဲေခါ္နိုင္ပါတယ္။
cdef ကိုသံုးရင္သတိထားစရာတစ္ခုရွိပါတယ္။ cdef declare function က python code ကိုမျမင္ရပါဘူး။ cdef ေခါ္တယ္ဆို Python ေရးေနတာထက္ C ေရးေနတဲ့လိုေျပာရင္ပိုမွန္ပါလိမ့္မယ္။
cpdef ကေတာ့ speed အရဆို python ရဲ့ def ထက္ျမန္ေပမယ့္ cdef ထက္ေနွးပါတယ္ ဒါေပသိ Python ေကာ Cython ေကာကပါ cpdef ကိုေခါ္နုိင္ပါတယ္။
 def function_name(...):  
   
 cdef functoin_name(...):  
   
 cpdef functoin_name(...):  

That's all for Cython #2
To be continue

PyLab (c) 2016

Pylab

Developer

Keep calm and love Python

0 comments:

Post a Comment