# Compared with Java and C++
:
Number:
type(a)
=> return type of a; or instance(a, int)
=> return true or false/
得到浮点数, //
得到整数,%
取余数,**
乘方String:
print("a number:", 666)
a,b = b,a
is able to swap the value of a,bprint()
will auto change to a new line, print(a. End=‘ ’)
is able to end the output line with “,”我也搞不清楚这里的List, Dict, Tuple到底是variable还是collections。是和JS一样所有东西都作为variables?
但是分别对应array,map,和。。。啥
[:]
代表全长str[:2]
是取[0,2)的数字,str[1:4]
是取得[1:4)的数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
myTup = (1,2,3)
; List: myList = [1,2,3]
tup3 = tup2[:1] + tup1[:1]
del tup3
,但是不能只删除某个元素myDict = {key1 : val1.1, key2 : val2}
myDict[key1]
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)
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
没啥特别的
def myFunc(para1):
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:
sum = lambda arg1, arg2: arg1 + arg2;
print ("相加后的值为 : ", sum( 10, 20 )) // 30
from ... import ...
from ... import *
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不会报错
包是一个分层次的文件目录结构,它定义了一个由模块及子包,和子包下的子包等组成的 Python 的应用环境。
简单来说,包就是文件夹,但该文件夹下必须存在 init.py 文件, 该文件的内容可以为空。init.py 用于标识当前文件夹是一个包。
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)
del obj
to delete an object__init__
: constructor; __del__
: 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而没有删除这个对象??
class A: # 定义类 A
.....
class B: # 定义类 B
.....
class C(A, B): # 继承类 A 和 B
.....
sort()
and sorted()
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)
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))
含有yield的函数,迭代的时候使用,不过我感觉容易写错,用的也不是很广。碰到了再整理
constructor
定义此方法,str(object)就会返回此方法的数据
和__str__()差不多
定义什么叫做<,返回值是boolean
定义什么叫做=, 返回值是boolean