从c++转到Python需要注意的地方

来源:互联网 发布:德乌洛费乌赛季数据 编辑:程序博客网 时间:2024/05/18 00:24

下面的资料,会随着学习的不断深入,持续的更新。

内容没有能有效的组织,因为没一点是本人再学习的过程中,慢慢的总结出来的。等本篇文字足够长的时候,可能会考虑组织文件可读性更强的文字。

 

1. c/c++里面,注释代码是用 // ,而python是用 #

 

 2. c/c++里面,定义类对象

 

[html] view plain copy print ? 
  1. // define class  
  2. class ClassA  
  3. {  
  4. ...  
  5. };  
  6. //////////////////////////////////////////////////////////////  
  7. ClassA OA; // 对象  
  8. ClassA *pA = new ClassA; // 指针  



而python里面

[html] view plain copy print ? 
  1. # define class  
  2. class ClassA:  
  3.     def func( self, name ):  
  4.         #do something  
  5.   
  6.    
  7. # declare a object of the class  
  8. ca = ClassA()  
  9.   
  10. ca.func( 'myname' )  



 

3.  c/c++主要依靠语句开始结束来判定语句块,如 “{ } , ;”这些。 而python靠的是缩进,缩进四个空格,不是一个tab,因为tab根据所使用的文本编辑不一样,所代表的空格数量不一样,有些是4,有些是8.

 

4. python类的成员函数都必须有一个self的参数传进去,self相当于c/c++的this。也就意味着成员函数至少有一个参数,不想c/c++可以没有参数。

 

5. 继承语法不一样,下面看下的python的类继承。

[python] view plain copy print ? 
  1. class ClassA:  
  2.     def funca( self, name ):  
  3.         #do something   
  4.   
  5. class ClassB(ClassA):  
  6.     def funcb( self, name ):  
  7.         #do something  


 6. python没有main函数,我们的c/c++都是以main为入点函数。但是python没有入点函数,而是从py文件的第一行就开始执行

 

7. c/c++里面字符串是用双引号""来修饰,而python则是用单引号 '', 或者是双引号""

[python] view plain copy print ? 
  1. char *p = "hello";  
  2.   
  3. p='hello'  


 

8.  打印语句,print在2.7以前的版本print可以写成:

print 'hello world'

或者

print ( 'hello world' )

但是2.7以后第一种格式不被支持。

 

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

下面给些样例代码,windows下面这些代码你可以直接ctrl+c, ctrl+v到你的记事本,然后保存成以py为后缀的文件你就可以直接执行;linux下面将下面的这些代码拷贝到一个新建的以py为后缀的文件,在文件的最开始加上#!/usr/bin/python,这行代码其实就是指定要用那个python解释器去执行该脚本。

 

[python] view plain copy print ? 
  1. <PRE class=python name="code"># test simple print   
  2. print 'hello world'  
  3. name = 'myname'  
  4. print 'hello %s' %name  
  5.   
  6. # define variables   
  7. max=10000  
  8. min=1  
  9. useridbase='2012FFD_'  
  10.   
  11. # define a function to print string  
  12. def MyPrint( str ):  
  13.  print str  
  14.    
  15. # define a function to do somthing  
  16. def UpdateUserID( id ):  
  17.  idd = id + 1  
  18.  idCur = '%s' %idd  
  19.  useridCurrent = useridbase+idCur  
  20.  print 'user name: %s' %useridCurrent  
  21.  return id+1  
  22.   
  23. # define class   
  24. class cTest1:  
  25.  def func1( self, name ):  
  26.   print 'hello %s', name  
  27.  def add( self, a, b ):  
  28.   return a + b  
  29.     
  30. # test class   
  31. c1=cTest1()  
  32. c1.func1('my class')  
  33. res = c1.add(3,22)  
  34. print 'sum is %s' %res  
  35.    
  36. # for loop, and call funtions we defined above  
  37. for n in xrange( min, max ):  
  38.  str = 'now user with no %s login' %n  
  39.  MyPrint( str )  
  40.  UpdateUserID( n )  
  41.   
  42. </PRE><BR>  
  43. <PRE></PRE>  
  44. <P> </P>  
  45. <PRE></PRE>  
  46. <P> </P>  
  47. <PRE></PRE>  
  48. <P><STRONG>9.  全局变量,python中使用全局变量时必须加上global关键字,否则被视为局部变量或者未定义。</STRONG></P>  
  49. <PRE class=html name="code">g_user = 0  
  50.   
  51. def UseGlobalVar():  
  52.     global g_user  
  53.     if ( g_user == 0 ):  
  54.         #do something</PRE>   
  55. <P><BR>  
  56. <STRONG>10. 如果忘了给变量/对象赋值,直接使用这个对象的方法就会被告知,这个对象没有这个方法。</STRONG></P>  
  57. <P>这点很让我恶心,也是c/c++转过来的人很难适应的地方,在c/c++中,这个对象有没有这个方法主要看这个对象对应的类,有没有这个方法。为什么python不能提供像javascript的那种特性,既可以定义为无类型,也可以定义某一类型的变量。也正因为这样,python的类型可以几乎没有。</P>  
  58. <PRE class=html name="code">class classA:  
  59.     def func( self ):  
  60.         # do something here   
  61.   
  62. Obj_classA = None  
  63.   
  64. print'testing start' )  
  65. #Obj_classA = new ClassA()   
  66. Obj_class.func()</PRE>  
  67. <P> </P>  
  68. <P>其实如果说提示的是Obj_classA这个对象没有一个对应的类型,还是可以理解的。而不是没有这个方法。</P>  
  69. <P> </P>  
  70. <P><STRONG>11. python中变量可以赋任意类型的值<BR>  
  71. </STRONG></P>  
  72. <PRE class=html name="code"><STRONG>var = 12  
  73. var = 'hello'  
  74. var = [ 3222 ]  
  75. print ( var )</STRONG></PRE>  
  76. <P><BR>  
  77. 上面这些代码没有任何问题,最后打印出的是 [3 , 222 ].</P>  
  78. <P>其实这点我很不喜欢,弱类型或者无类型就有可能导致一些bug,而不容易被查出。</P>  
  79. <P> </P>  
  80. <P><STRONG>12. 求地址,c/c++通过&, 而python通过一个函数id函数</STRONG></P>  
  81. <PRE class=html name="code">a = 1  
  82. b = a  
  83. print( id( a ))  
  84. print( id( b ))</PRE>  
  85. <P><BR>  
  86.  </P>  
  87. <P>id()这个函数返回的是对象的全部唯一标识符,是整型或者长整型的数字,可以看做是对象的地址。</P>  
  88. <P> </P>  
  89. <P> </P>  
  90. <P><STRONG>13. 命名空间。c/c++是通过namespace关键字来定义和使用,而python中,这个东西没有用特别的关键字表示,而是一个python脚本文字自动被认为一个命名空间,而这个命名空间的名字就是文件的名字</STRONG>。</P>  
  91. <P>如我们有2个文件,一个定义函数和变量,另外一个则使用这些函数和变量。</P>  
  92. <PRE class=html name="code">#FuncAssembly.py  
  93.   
  94. count = 0  
  95.   
  96. def UserPass():  
  97.     global count  
  98.     count++  
  99.     return count  
  100.   
  101. def UserCancel():  
  102.     global count  
  103.     count--  
  104.     return count  
  105. </PRE>  
  106. <P><BR>  
  107.  </P>  
  108. <PRE class=html name="code">import FuncAssembly  
  109. #from FuncAssembly import *   
  110. #from FuncAssembly import UserPass   
  111.   
  112. print'start testing' )  
  113. res = FuncAessembly.UserPass()   
  114. print( res )</PRE>  
  115. <P><BR>  
  116.  </P>  
  117. <P>看到了吧,第二个文件要使用第一文件,只要import进来就可以了,import有点类似c/c++的#include。这个时候第一个文件的文件名就是它的命名空间,使用它的变量或者函数的时候,必须加上命名空间。</P>  
  118. <P> </P>  
  119. <P><STRONG>14. python的与或关系不是c/c++的 && 和 ||。而是直接使用自然语言 and 和 or</STRONG></P>  
  120. <P> </P>  
  121. <STRONG></STRONG><PRE class=html name="code">a = 1  
  122. b = 2  
  123. if (( a==1 ) and ( b == 2 )):  
  124.     print'all are correct' )  
  125.   
  126. if (( a == 1 ) or ( b == 3 )):  
  127.     print'some a is correct' )</PRE>  
  128. <P><BR>  
  129.  </P>  
  130. <P><STRONG>15. python中等于和不等于除了可以用==和!=来表示,还可以直接使用自然语言 is 和 is not</STRONG>  </P>  
  131. <PRE class=html name="code">a = 1  
  132. if ( a is 1 ):  
  133.    print'is' )  
  134. if ( a is not 2 ):  
  135.     print'not' )</PRE>  
  136. <P><BR>  
  137.  </P>  
  138. <P>16. python的关键字:</P>  
  139. <P><STRONG><SPAN style="COLOR: #3333ff">and </SPAN></STRONG></P>  
  140. <P><STRONG><SPAN style="COLOR: #3333ff">del </SPAN></STRONG></P>  
  141. <P><STRONG><SPAN style="COLOR: #3333ff">from </SPAN></STRONG></P>  
  142. <P><STRONG><SPAN style="COLOR: #3333ff">not </SPAN></STRONG></P>  
  143. <P><STRONG><SPAN style="COLOR: #3333ff">while </SPAN></STRONG></P>  
  144. <P><STRONG><SPAN style="COLOR: #3333ff">as </SPAN></STRONG></P>  
  145. <P><STRONG><SPAN style="COLOR: #3333ff">elif </SPAN></STRONG></P>  
  146. <P><STRONG><SPAN style="COLOR: #3333ff">global </SPAN></STRONG></P>  
  147. <P><STRONG><SPAN style="COLOR: #3333ff">or </SPAN></STRONG></P>  
  148. <P><STRONG><SPAN style="COLOR: #3333ff">with </SPAN></STRONG></P>  
  149. <P><STRONG><SPAN style="COLOR: #3333ff">assert </SPAN></STRONG></P>  
  150. <P><STRONG><SPAN style="COLOR: #3333ff">else </SPAN></STRONG></P>  
  151. <P><STRONG><SPAN style="COLOR: #3333ff">if </SPAN></STRONG></P>  
  152. <P><STRONG><SPAN style="COLOR: #3333ff">pass </SPAN></STRONG></P>  
  153. <P><STRONG><SPAN style="COLOR: #3333ff">yield </SPAN></STRONG></P>  
  154. <P><STRONG><SPAN style="COLOR: #3333ff">break </SPAN></STRONG></P>  
  155. <P><STRONG><SPAN style="COLOR: #3333ff">except </SPAN></STRONG></P>  
  156. <P><STRONG><SPAN style="COLOR: #3333ff">import </SPAN></STRONG></P>  
  157. <P><STRONG><SPAN style="COLOR: #3333ff">print</SPAN></STRONG></P>  
  158. <P><STRONG><SPAN style="COLOR: #3333ff">class </SPAN></STRONG></P>  
  159. <P><STRONG><SPAN style="COLOR: #3333ff">exec </SPAN></STRONG></P>  
  160. <P><STRONG><SPAN style="COLOR: #3333ff">in </SPAN></STRONG></P>  
  161. <P><STRONG><SPAN style="COLOR: #3333ff">raise </SPAN></STRONG></P>  
  162. <P><STRONG><SPAN style="COLOR: #3333ff">continue </SPAN></STRONG></P>  
  163. <P><STRONG><SPAN style="COLOR: #3333ff">finally </SPAN></STRONG></P>  
  164. <P><STRONG><SPAN style="COLOR: #3333ff">is </SPAN></STRONG></P>  
  165. <P><STRONG><SPAN style="COLOR: #3333ff">return </SPAN></STRONG></P>  
  166. <P><STRONG><SPAN style="COLOR: #3333ff">def </SPAN></STRONG></P>  
  167. <P><STRONG><SPAN style="COLOR: #3333ff">for </SPAN></STRONG></P>  
  168. <P><STRONG><SPAN style="COLOR: #3333ff">lambda </SPAN></STRONG></P>  
  169. <P><STRONG><SPAN style="COLOR: #3333ff">try </SPAN></STRONG></P>  
  170. <P><STRONG><SPAN style="COLOR: #3333ff">None </SPAN></STRONG></P>  
  171. <P> </P>  
  172. <P>17. 字符串加和操作。python中字符串可以简单的加和:</P>  
  173. <PRE class=html name="code">str1 = 'hello ' + 'world'  
  174. str2 = 'hello' 'world'  
  175. print ( str1 )  
  176. print ( str2 )</PRE>  
  177. <P><BR>  
  178. <BR>  
  179.  </P>  
  180. <P>这里顺便说下str是python的内置类型,所以不要把你的变量的名字定义为str。</P>  
  181. <P>上面的str1和str2的内容是一样,2中字符串的连接是等效的。但是第二种方式的操作符不能使变量,即:</P>  
  182. <P>str3 = 'simple'</P>  
  183. <P>str2 = str3 'string' #语法错误</P>  
  184. <P>是不可以的。必须要用第一种:</P>  
  185. <P>str3 = 'simple'</P>  
  186. <P>str2 = str3 + 'string'</P>  
  187. <P> </P>  
  188. <P>格式化字符串也很方便:</P>  
  189. <PRE class=html name="code">a = 1  
  190. b = 'string'  
  191. ss = 'ss string is {0} and {1}'.format( a, b )  
  192. print( ss )</PRE>  
  193. <P><BR>  
  194.  </P>  
  195. <P>上面的结果是</P>  
  196. <P>ss string is 1 and string</P>  
  197. <P> </P>  
  198. <P><STRONG>18. 格式化字符串</STRONG></P>  
  199. <PRE class=html name="code">str1 = 'hello'  
  200. str2 = 'world'  
  201. num1 = 8  
  202. str3 = '%(string1)s my %(string2)s, integer is %(number1)03d' %{'string1':str1, 'string2':str2, 'number1':num1}  
  203. print( str3 )</PRE>  
  204. <P><BR>  
  205.  </P>  
  206. <P>上面输出的结果是</P>  
  207. <P>hello my world, integer is 008</P>  
  208. <P> </P>  
  209. <P>19. python中,没有public, protected, private来描述class的成员,而是通过成员的前缀来区分是public的还是private的,如果有 ‘__’(注意是2个下划线)就表示私有的,如果没有就是公有的。</P>  
  210. <PRE class=html name="code">class myclass:  
  211.     name = ''  
  212.     __name1 = ''  
  213.     def __privatefunc( sef ):  
  214.         print'cannot be called outside' )  
  215.     def ini( self ):  
  216.         print'hello' )  
  217.     def create( self, name ):  
  218.         self.name = name  
  219.         print'now create' )  
  220.   
  221.   
  222. mc = myclass()  
  223. mc.ini()  
  224. mc.create( 'myname' )  
  225. mc.name = 'changed'  
  226. mc.__privatefunc() #错误   
  227. </PRE>  
  228. <P>mc.__name1 = 'name' #错误<BR>  
  229. </P>  
  230. <P> </P>  
  231. <P>上面的代码声明了__name1和__privatefunc()为私有的,因此最后两句会导致错误。</P>  
  232. <P>不过要说一下,python这里是做了一个小把戏,其实是在运行时修改了这种属性的名字,该规则是 _类名+属性名,在上面的例子中改后的名字为:</P>  
  233. <P>_myclass_privatefunc,知道了这个规则后,就可以访问到这个所谓的私有方法。其实用python内置的方法 dir()就可以看到改变的名字。</P>  
  234. <P> </P>  
  235. <P><STRONG>20. python不可以像c/c++那样,进行强制类型转换</STRONG>,<STRONG>但是可以像下面那样构造一个新的对象来达到这种效果</STRONG></P>  
  236. <PRE class=html name="code">s1='hello world'  
  237. l1=(list)s1  #错误   
  238. l1=list(s1)  #正确</PRE>   
  239. <P><BR>  
  240.  </P>  
  241. <P><STRONG>21. ++和--在python不支持,如果做到同样的效果改为 +=和 -=</STRONG><BR>  
  242.  </P>  
  243. <PRE class=html name="code">a = 1L  
  244. a++  #错误   
  245. a += 1L #正确</PRE>  
  246. <P><BR>  
  247. </P>  
  248. <P><STRONG>22. python中不能用static来定义一个静态方法(c++中就是这样定义的),static不是python的关键字。但是python还是可以定义静态方法的:</STRONG></P>  
  249. <P></P>  
  250. <PRE class=html name="code">class classA: 
  251.     @staticmethod  
  252.     def func( s ):  
  253.         print( s )</PRE><BR>  
  254. classA.func( 'test' )  
  255. <P></P>  
  256. <P></P>  
  257. <P></P>  
  258. <P></P>  
  259. <P></P>  
  260. <P></P>  
  261. <P></P>  
  262. <P><BR>  
  263. </P>  
  264. <P>但是不要想当然的,使用@staticvariable来定义静态成员变量,python中是不可以定义静态变量的。<BR>  
  265. </P>  
  266. <P><BR>  
  267. </P>  
  268. <P><STRONG>23. python中不用显示写函数的返回类型,或者表明函数返回一个东西. 并且默认会返回一个None,如果你的函数没有写任何return语句的话,否则返回你自己的类型。None是python的关键字。</STRONG></P>  
  269. <PRE class=python name="code"> </PRE><PRE class=python name="code">def func():  
  270.     print'simple test' )  
  271.   
  272. if ( None == func()):  
  273.     print'correct' )</PRE>  
  274. <P><BR>  
  275.  </P>  
  276. <P><STRONG>24. c++和python都是面向对象的语言,那么就自省的能力,至于什么自省的能力,请参看我的另外一篇文章。C++的自省是依靠typeid(),而python是通过2个内置的方法:isinstance()和hasattr()</STRONG></P>  
  277. <PRE class=python name="code">class CA:  
  278.     x = 'name'  
  279.     def func( self ):  
  280.         print( x )  
  281.   
  282. a = CA()  
  283. print( isinstance( a, CA ))    输出->True  
  284. print( hasattr( a, 'func' ))   输出->True</PRE>  
  285. <P><BR>  
  286.  </P>  
  287. <P> </P>  
  288. <P><STRONG>25. python可以直接在类中嵌入类的说明,然后通过 __doc__来访问说明:</STRONG></P>  
  289. <PRE class=python name="code">class CA( object ):  
  290.     "used to test a class that is derived from base class-object"  
  291.     def func( this ):  
  292.         print'this is ref to object' )  
  293.   
  294. a = CA()  
  295. print( a.__doc__ )  输出->"used to test a class that is derived from base class-object"</PRE>  
  296. <P><BR>  
  297.  </P>  
  298. <P><STRONG>26. python中,类的继承过程中,可以把类中所有方法视为c++的虚函数。</STRONG> </P>  
  299. <PRE class=python name="code">class CA:  
  300.     "the class is designed to test a class is defined without being derived from base class object"  
  301.     x = 0L 
  302.     @classmethod  
  303.     def func( sef ):  
  304.         print"CA func" ) 
  305.          
  306.     @classmethod  
  307.     def func1( self ):  
  308.         print"CA func1" ) 
  309.          
  310.     @classmethod  
  311.     def __privateFunc( self ):  
  312.         print"CA private func " ) 
  313.  
  314.     @staticmethod  
  315.     def staticfunc():  
  316.         print"CA static function" )  
  317.   
  318. class CCA( CA ):  
  319.     def func( slef ):  
  320.         print"CCA func" )  
  321.   
  322. print'test class derivation' )  
  323. cca = CCA()  
  324. cca.func()     #输出->CCA func   
  325. </PRE>  
  326. <P><BR>  
  327. <BR>  
  328.  </P>  
  329. <P><STRONG>27. c++的构造函数和析构函数的名字基于类的名字,但是python的构造函数固定为 __init__(),析构函数固定为 __del__()。</STRONG>详细的内容请参看我的另外一篇博文:</P>  
  330. <P><A href="http://blog.csdn.net/huangxiansheng1980/article/details/7227915" wrc-processed="done">http://blog.csdn.net/huangxiansheng1980/article/details/7227915</A><SPAN style="WIDTH: 16px; PADDING-RIGHT: 16px; HEIGHT: 16px" class=wrc11 onmouseover="if(window!=window.top) return false; window.top.WRCShowContent({'rating': {'value': 95, 'weight': 15}, 'flags': {'shopping': 0, 'social': 0, 'news': 0, 'it': 0, 'corporate': 0, 'pornography': 0, 'violence': 0, 'gambling': 0, 'drugs': 0, 'illegal': 0}, 'ttl': 7200, 'visited': 1}, this.className); return true;" onmouseout="if(window!=window.top) return false; cancel = false; window.setTimeout(window.top.WRCHideContent, 1000);"> </SPAN></P>  
  331. <P> </P>  
  332. <P>  </P>  
  333. <P>28. python的函数参数可以任意的顺序传进去如果指定了参数的名字</P>  
  334. <P>下面是测试代码:<BR>  
  335. </P>  
  336. <P>def simplefunc( d, username, password ):<BR>  
  337.         print'id:{0}'.format( d ) )<BR>  
  338.         print'username:{0}'.format( username ))<BR>  
  339.         print'password:{0}'.format( password ))<BR>  
  340. <BR>  
  341. def testsimple():<BR>  
  342.         i = 1<BR>  
  343.         un = 's1'<BR>  
  344.         pw = '123'<BR>  
  345.         print 'test1=================='<BR>  
  346.         simplefunc( i, un, pw )<BR>  
  347.         print 'test2=================='<BR>  
  348.         simplefunc( username=un, password=pw, d=i)<BR>  
  349.         print 'test3==================='<BR>  
  350.         simplefunc( password=pw, d=i, username=un)<BR>  
  351. </P>  
  352. <P><BR>  
  353. </P>  
  354. <P>>>> from funcDef import *<BR>  
  355. >>> testsimple()<BR>  
  356. test1==================<BR>  
  357. id:1<BR>  
  358. username:s1<BR>  
  359. password:123<BR>  
  360. test2==================<BR>  
  361. id:1<BR>  
  362. username:s1<BR>  
  363. password:123<BR>  
  364. test3===================<BR>  
  365. id:1<BR>  
  366. username:s1<BR>  
  367. password:123<BR>  
  368. </P>  
  369. <P><BR>  
  370. </P>  
  371. <P>未完待续...</P>  
  372. <PRE></PRE>  
  373. <PRE></PRE>  
  374. <PRE></PRE>  
  375. <PRE></PRE>  
  376. <PRE></PRE>  
  377. <PRE></PRE>  
  378. <PRE></PRE>  
  379. <PRE></PRE>  
  380. <PRE></PRE>  
  381. <PRE></PRE>  
  382. <PRE></PRE>  
  383. <PRE></PRE>  
  384. <PRE></PRE>  
  385. <PRE></PRE>  
  386. <PRE></PRE>  
  387. <PRE></PRE>  
  388. <PRE></PRE>  
  389. <PRE></PRE>  
原创粉丝点击