# Compared with Java and C++
Basic Syntax
- 没有分号;通过intent控制
- if 语句,for,while都没有括号,但是要用冒号
:
- method argument 还是有()的
Variables
Number:
- Python has weak type, 创建时必须被赋值
- 数据类型(6种)包括:Number, String, List, Tuple, Set, Dictionary
- Number,String,Tuple不可变(大概和Java里面String,Array不可变一样?Java有StringBuffer,ArrayList,Python怎么办?)
- Number:int(10,0x10) float(10.0,6.02E-23) bool(True) complex(1+2j)
type(a)
=> return type of a; orinstance(a, int)
=> return true or false
Number opearations:/
得到浮点数,//
得到整数,%
取余数,**
乘方
String:
- 0为正数第一个,-1为倒数第一个。
- + 连接字符串,*赋值字符串
- string[i:j],slice操作,相当于c++ substr(i,j)
- string[index],就是inspect第i个元素
- string是不可修改类型,如何修改字符串?参考
Input and Output
- A simple sample:
print("a number:", 666)
- how to give value to a variable:
a,b = b,a
is able to swap the value of a,b
print()
will auto change to a new line,print(a. End=‘ ’)
is able to end the output line with “,”
Collections
我也搞不清楚这里的List, Dict, Tuple到底是variable还是collections。是和JS一样所有东西都作为variables?
但是分别对应array,map,和。。。啥
list
- index is the same as string
[:]
代表全长 str[:2]
是取[0,2)的数字,str[1:4]
是取得[1:4)的数- + and * is the same as String
- 就是可变字符串=>Java ArrayList, StringBuffer的综合吧大概
Sample
# easy to make mistakes
myList1 = [] ; myList3 = []
myList2 = [1]
myList1.append(myList2) // [1]
myList3.append(list(myList2)) // deepcopy [1]
myList2 = [2]
print(myList1) // [2]
print(myList3) // [1]
List Method:
// don't have to be the same type
myList = ['Google', 'Baidu', 1997, 1998]
// 1. modify the List
// in the end of the List
myList.append(obj) // 接受一个对象
myList.extend(obj) // 接受一个列表作为对象
myList.count(obj)
myList.insert(index, obj)
// remove an element
myList.pop() // remove the last element
myList.remove(obj) // remove the fisrt corespond element
myList.clear() // remove all
del [index] // not the objuct method
// 2.
len(myList)
max(myList)
min(myList)
list(seq) // turn tuple into list
Tuple
- Tuple:
myTup = (1,2,3)
; List:myList = [1,2,3]
- 不允许修改,但是可以
tup3 = tup2[:1] + tup1[:1]
- 可以
del tup3
,但是不能只删除某个元素
Dict
- elements不一定是同一种type
myDict = {key1 : val1.1, key2 : val2}
- 通过key访问val:
myDict[key1]
- 同一个key出现两次,后一个会被记住
- key必须为不可变的类型:Number, String,Tuple; List is not allowed
Dict Method
myDict = {key1 : val1, key2 : val2}
// 1. modify the dict
myDict[key1] = val3
myDict[key1] = set([val3])
// remove ele or dict
myDict.clear() // remove all
del myDict[key1]
del myDict
// 2.
len(myDict)
str(myDict) // turn the dict into string
// 3.
myDict.copy() // shallow copy
key in myDict // return boolean
myDict.items() // return a tuple, including key and val
myDict.keys() // return type dict_keys?? => keys = list(myDict.keys)就可以得到list了
myDict.values()
myDIct.get(key) // if not exist, return default value(type:NoneType; 打印的话为None)
set
- 无序不重复元素序列
- 创建空集合set(), 创建空字典{}
- a little different to the set in java or cpp
- there are operations: intersection, union, complement
- also can add, remove, clear like set in java or cpp
allocated in heap or stack?
If and Loop
if… else
if condition:
// to do something
elif:
// to do something
else:
// to do domething
// && is and, || is or
for loop
for each更常用
for letter in 'Python':
print '当前字母 :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits:
print '当前水果 :', fruit
也可以用index
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print '当前水果 :', fruits[index]
for… else (我第一次见)
for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。
for i in range(1,10):
// do something
else:
// do something
while loop
没啥特别的
Function
- 函数代码块以 def 关键词开头,后接函数标识符名称和圆括号()
def myFunc(para1):
- return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None
- 重点: 传参数和Java一样是值传递(复制一份),我也可以传一个对象的引用。
- 关于参数传递问题,我受c++影响,故参考此文章。
- Python有不定长参数和默认参数
def printinfo(*vartuple ):
"打印任何传入的参数"
print ("输出: ")
for var in vartuple:
print (var)
# 调用printinfo 函数
printinfo( 10 ) // 10
printinfo( 70, 60, 50 ) // 70 60 50
Using lamda to define anonymous function:
- lambda的主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。
- lambda函数拥有自己的命名空间(namespace),且不能访问自有参数列表之外或全局命名空间里的参数。
sum = lambda arg1, arg2: arg1 + arg2;
print ("相加后的值为 : ", sum( 10, 20 )) // 30
Module
from ... import ...
from ... import *
Python的命名空间(全局,局部变量):
- Python 会猜测一个变量是局部的还是全局的,它假设任何在函数内赋值的变量都是局部的。 (函数内使用全局变量需要用global)
Money = 2000 // Money is global
def AddMoney():
# 想改正代码就取消以下注释:
# global Money
Money = Money + 1 // Money turns to be local
print (Money) // 2000
AddMoney()
print (Money) // UnboundLocalError
// 在AddMondy内部定义global Money, 第二个print Money不会报错
Package ??
包是一个分层次的文件目录结构,它定义了一个由模块及子包,和子包下的子包等组成的 Python 的应用环境。
简单来说,包就是文件夹,但该文件夹下必须存在 init.py 文件, 该文件的内容可以为空。init.py 用于标识当前文件夹是一个包。
Python OOP
sample:
class Employee:
// 不用写private, public 之类的,默认public
empCount = 0
// private variable,前面加下划线就好了
__privateCount = 1;
// protected varaible
_protectedCount = 2;
def __init__(self, name, salary):
// 强制使用self,且必须作为arguments传进来
// __init__ 即constructor
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
// 强制传self
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
// 强制使用self
print ("Name : ", self.name, ", Salary: ", self.salary)
object
- GC: 反正是自动的
del obj
to delete an object
class
__init__
: constructor;__del__
: destructor- 对象实例化的时候调用constructor,对象不再使用的时候调用destructor
class Point:
def __init__( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print class_name, "销毁"
pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # 打印对象的id
del pt1
del pt2
del pt3
// 3083401324 3083401324 3083401324
// Point 销毁
把pt1, pt2,pt3都删了才调用destructor??也就是说del只是删除了pointer而没有删除这个对象??
inheritance
- 允许多重继承
class A: # 定义类 A
.....
class B: # 定义类 B
.....
class C(A, B): # 继承类 A 和 B
.....
- 构造方法的继承: 不重写则会默认不改 => Python 子类继承父类构造函数说明
- override methods: 直接重新写一遍就好了
内置函数和对象的方法
1.
# List
numbers = [1, 3, 4, 2]
# Sorting list of Integers in ascending
numbers.sort()
# Sorting list of integers in descending
numbers.sort(reverse = True)
2.
# Using user defined sorting rule
def sortSecond(val):
return val[1]
# list1 to demonstrate the use of sorting
# using using second key
list1 = [(1, 2), (3, 3), (1, 1)]
# sorts the array in ascending according to
# second element
list1.sort(key = sortSecond)
print(list1)
# sorts the array in descending according to
# second element
list1.sort(key = sortSecond, reverse = True)
print(list1)
Iterator and Generator
Iterator
python也有iterator等,但是功能比cpp少了很多,感觉主要还是用来遍历
先来看iterator的原理:
class MyNumbers:
def __iter__(self):
// 不管怎么着,创建iterator对象的时候都指向第一个
self.a = 1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
// 可以不加,是用来限制迭代次数,防止无限循环的
raise StopIteration
// 如何使用
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
Generator
含有yield的函数,迭代的时候使用,不过我感觉容易写错,用的也不是很广。碰到了再整理
定义class 的方法
init(self)
constructor
__ del__()
str()
定义此方法,str(object)就会返回此方法的数据
__ repr__()
和__str__()差不多
lt(self, other)
定义什么叫做<,返回值是boolean
eq(self, other)
定义什么叫做=, 返回值是boolean