Python是一門高級、通用用途、多范式、動態類型、解釋型程序設計語言。
def sayHello:
print("Hello World!")
if __name__ == "__main__":
sayHello()
用Python解釋器執行:
python helloworld.py
TBD
Python支持多種編程范式,包括:
過程式編程的核心概念是:數據結構和過程。Python中,數據結構由類實現,過程由函數實現。
使用Class定義雙向鏈表的節點:
>>> class Node:
... def __init__(self):
... self.value = None
... self.previous = None
... self.next = None
...
使用Class的構造器創建Node實例,並讀寫成員字段:
>>> head = Node()
>>> head.value=0
>>> second = Node()
>>> second.value=1
>>> head.next = second
>>> second.previous = head
>>> head.value
0
>>> head.next.value
1
使用def定義一個Fibonacci函數:
>>> def fibo(n):
... if n == 0:
... return 1
... if n == 1:
... return 1
... return fibo(n-1) + fibo(n-2)
...
調用函數:
>>> fibo(10)
89
Objecte Oriented 的核心元素是Class和Object。Object Oriented的四大特性是:
Class聲明主要包括:
class ClassName(BaseClassName):
def __init__(self):
self.name = "default"
def otherMethod(self, parameters):
# do something
Class使用關鍵字class
聲明。
基類可選,默認為object
。
構造器固定名字為__init__
。
字段在構造器中顯示聲明。
方法的第一個參數必需是self - object自身。
使用構造器方法創建對象:
aObject = ClassName()
TBD
TBD
TBD
class Person:
def __init__(self, name):
self.__name = name
def sayHello(self):
print("Hello "+self.__name)
def rename(self, newName):
self.__name = newName
>>> a = Person("Bob")
>>> a.__name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Person' object has no attribute '__name'
>>> a.sayHello()
Hello Bob
>>> a.rename("Mike")
>>> a.sayHello()
Hello Mike
單繼承
多繼承
TBD
Interface
TBD
Overload
Override
TBD
TBD
Python內建了List、Tuple、Set和Dictionary四個常用數據類型。
List是一個有序的、可變的集合。使用List可以實現Stack。
>>> a = []
>>> a
[]
>>>
>>> a = [1,2,3]
>>> a
[1, 2, 3]
>>>
>>> a = [1,2,3]
>>> a
[1, 2, 3]
>>> a.append(4)
>>> a
[1, 2, 3, 4]
>>>
>>> a = [1,2,3]
>>> a
[1, 2, 3]
>>> a.insert(1,10)
>>> a
[1, 10, 2, 3]
>>>
>>> a = [1,2,3]
>>> a
[1, 2, 3]
>>> a.remove(2)
>>> a
[1, 3]
>>>
>>> a = [1,2,3]
>>> a
[1, 2, 3]
>>> del a[1]
>>> a
[1, 3]
>>>
>>> a = [1,2,3]
>>> a
[1, 2, 3]
>>> a[1]
2
>>>
>>> a = [1,2,3,4]
>>> a
[1, 2, 3, 4]
>>> a[1:3]
[2, 3]
>>>
>>> a = [1,2,3]
>>> a
[1, 2, 3]
>>> a.append(4)
>>> a
[1, 2, 3, 4]
>>>
>>> a = [1,2,3,4]
>>> a
[1, 2, 3, 4]
>>> a.pop()
4
>>>
Tuple是不可變的List。
>>> a = ()
>>> a
()
>>>
>>> a = (1,2,3)
>>> a
(1, 2, 3)
>>>
>>> a = (1,2,3)
>>> a
(1, 2, 3)
>>> a[1]
2
>>>
>>> a = (1,2,3)
>>> a
(1, 2, 3)
>>> one, two, three = a
>>> one
1
>>> two
2
>>> three
3
>>>
Set是無序的、不包含重復元素的集合。
>>> s = {}
>>> s
{}
>>>
>>> s = {1,2,3}
>>> s
{1, 2, 3}
>>> s = {1,2,3}
>>> s
{1, 2, 3}
>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>> s = {1,2,3}
>>> s
{1, 2, 3}
>>> s.remove(2)
>>> s
{1, 3}