1. Input From Keyboard
- input() ---> raw data as string
- eval() ---> inpute gets evaluated
會(huì)根據(jù)輸入的格式來轉(zhuǎn)換相應(yīng)的數(shù)據(jù)類型
2. Condition
if xxx:
xxx
elif xxx:
xxx
else:
xxx
max = a if (a > b) else b
3. Loop
while xxx:
xxx
else: //optional part
xxx
for <variable> in <sequence>:
<statements>
else: //optional part
<statements>
for i in range(len(fibonacci)):
xxx
- break可以跳過else的部分
- range(end) ---> 0 ~ end - 1
- range(begin,end) ---> begin ~ end - 1
- If you loop over a list, it's best to avoid changing the list in the loop body. ---> 用copy來for
colours = ["red"]
for i in colours[:]: //用copy來for
if i == "red":
colours += ["black"]
if i == "black":
colours += ["white"]
print(colours) //['red', 'black']
4. Function
- default para & docstring
def Hello(name="everybody"): //default para
""" Greets a person """ // docstring
print("Hello " + name + "!")
Hello("Peter") //Hello Peter!
Hello() //Hello everybody!
print(Hello.__doc__) //Greets a person
- Return Values
沒有return或者return后不接數(shù)據(jù)筹燕,函數(shù)返回None
- Returning Multiple Values
return (lub, new)
5. File management
- open & close & read
fobj = open("ad_lesbiam.txt", "r") // r:read --> optional
fobj = open("ad_lesbiam.txt")
for line in fobj:
print(line.rstrip())
fobj.close()
- write
fh = open("example.txt", "w")
fh.write("To write or not to write\nthat is the question!\n")
fh.close()
- 使用with來自動(dòng)close文件
with open("example.txt", "w") as fh:
fh.write("To write or not to write\nthat is the question!\n")
- 一次性read
readline() --> list
read() --> string
poem = open("ad_lesbiam.txt").readlines()
poem = open("ad_lesbiam.txt").read()
- 設(shè)置當(dāng)前讀寫位置
.seek(i) --> 移到 ith byte
.tell() --> 當(dāng)前位置
.read(i) --> 從當(dāng)前位置向后讀i bytes
6. Modules
Every file, which has the file extension .py and consists of proper Python code, can be seen or is a module!
- Import
import math
from math import * //same as above, not recommanded!
from math import sin, pi
import numpy as np //rename namespace
- Design Module
文件名就是module名
- Executing Modules as Scripts
if __name__ == "__main__":
import sys
fib(int(sys.argv[1]))
只有在run as sript時(shí)才運(yùn)行畏梆,import時(shí)不運(yùn)行
- Package
- It's possible to put several modules into a Package.
- 在包含多個(gè).py文件的文件夾下建一個(gè)
__init__.py
文件
from SimplePackage import a, b //包含a.py b.py
import SimplePackage //錯(cuò)誤猴仑!
7. Obeject-Oriented Programming
everything is a class in Python
class Robot:
pass
- Attributes
儲(chǔ)存在instance的一個(gè)dict里面
__dict__
- Method
第一個(gè)參數(shù)要是self
-
__init__
Method
對(duì)象創(chuàng)建時(shí)執(zhí)行的初始化
class Robot:
def __init__(self, name=None):
self.name = name
def say_hi(self):
if self.name:
print("Hi, I am " + self.name)
else:
print("Hi, I am a robot without a name")
x = Robot()
x.say_hi() //Hi, I am a robot without a name
y = Robot("Marvin")
y.say_hi() //Hi, I am Marvin
-
Data Abstraction, Data Encapsulation, Data Hiding
- Data Abstraction = Data Encapsulation + Data Hiding
- Encapsulation is often accomplished by : Gettter & Setter
__str__
&__repr__
__str__
--> 能夠讓對(duì)象被str()使用哗咆,但返回結(jié)果不可通過eval()轉(zhuǎn)回對(duì)象__repr__
-->能夠讓對(duì)象被repr()使用猎荠,且返回結(jié)果可通過eval()轉(zhuǎn)回對(duì)象當(dāng)只有
__str__
定義時(shí)闺阱,str()可用但repr()不可用忆嗜;當(dāng)只有__repr__
定義時(shí)映屋,兩個(gè)均可用Public > Protected > Private
通過命名前的下劃線來定義。袱讹。疲扎。
class Robot:
def __init__(self, name=None, build_year=2000):
self.__name = name
self.__build_year = build_year
def say_hi(self):
if self.__name:
print("Hi, I am " + self.__name)
else:
print("Hi, I am a robot without a name")
def set_name(self, name):
self.__name = name
def get_name(self):
return self.__name
def set_build_year(self, by):
self.__build_year = by
def get_build_year(self):
return self.__build_year
def __repr__(self):
return "Robot('" + self.__name + "', " + str(self.__build_year) + ")"
def __str__(self):
return "Name: " + self.__name + ", Build Year: " +
8. Class and Instance Attributes
- Static Method
即可以被class調(diào)用,也可以被instance調(diào)用
需要用@staticmethod
指明捷雕,不需要第一個(gè)參數(shù)self
class Robot:
__counter = 0
def __init__(self):
type(self).__counter += 1
@staticmethod
def RobotInstances():
return Robot.__counter
- Class Method
與Static Method的相同點(diǎn):即可以被class調(diào)用椒丧,也可以被instance調(diào)用
不同點(diǎn):第一個(gè)參數(shù)是class reference,因此方法中可以有class的信息
class Robot:
__counter = 0
def __init__(self):
type(self).__counter += 1
@classmethod
def RobotInstances(cls):
return cls, Robot.__counter
9. Property
- property decoration
@property
- 充當(dāng)getter & setter的角色
- 無getter & setter的情況下又能實(shí)現(xiàn)他們的功能
class P:
def __init__(self,x):
self.x = x
@property
def x(self): //getter
return self.__x
@x.setter
def x(self, x): //setter
if x < 0:
self.__x = 0
elif x > 1000:
self.__x = 1000
else:
self.__x = x
- 使用情況
- 如果某個(gè)attr需要被user使用救巷,則設(shè)計(jì)為public并定義它對(duì)應(yīng)的property
- 如果不需要被user使用壶熏,則設(shè)計(jì)為private
10. Inheritance
- 語(yǔ)法
class Person:
def __init__(self, first, last):
self.firstname = first
self.lastname = last
def Name(self):
return self.firstname + " " + self.lastname
class Employee(Person): //inheritance
def __init__(self, first, last, staffnum):
Person.__init__(self,first, last) // or super().__init__(first, last)
self.staffnumber = staffnum
def GetEmployee(self):
return self.Name() + ", " + self.staffnumber
x = Person("Marge", "Simpson")
y = Employee("Homer", "Simpson", "1007")
print(x.Name())
print(y.GetEmployee())
-
Overloading & Overiding
- Overriding -->對(duì)繼承下來的方法進(jìn)行新的定義
但是方法名,參數(shù)浦译,返回值類型保持不變
class Person:
def __init__(self, first, last, age):
self.firstname = first
self.lastname = last
self.age = age
def __str__(self):
return self.firstname + " " + self.lastname + ", " + str(self.age)
class Employee(Person):
def __init__(self, first, last, age, staffnum): //overriding
super().__init__(first, last, age)
self.staffnumber = staffnum
def __str__(self): //overriding
return super().__str__() + ", " + self.staffnumber