元哥3天學(xué)Python--Day3

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
  1. Attributes

儲(chǔ)存在instance的一個(gè)dict里面__dict__

  1. Method

第一個(gè)參數(shù)要是self

  1. __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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末棒假,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子精盅,更是在濱河造成了極大的恐慌帽哑,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,865評(píng)論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件叹俏,死亡現(xiàn)場(chǎng)離奇詭異妻枕,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)她肯,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,296評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門佳头,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人晴氨,你說我怎么就攤上這事康嘉。” “怎么了籽前?”我有些...
    開封第一講書人閱讀 169,631評(píng)論 0 364
  • 文/不壞的土叔 我叫張陵亭珍,是天一觀的道長(zhǎng)敷钾。 經(jīng)常有香客問我,道長(zhǎng)肄梨,這世上最難降的妖魔是什么阻荒? 我笑而不...
    開封第一講書人閱讀 60,199評(píng)論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮众羡,結(jié)果婚禮上侨赡,老公的妹妹穿的比我還像新娘。我一直安慰自己粱侣,他們只是感情好羊壹,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,196評(píng)論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著齐婴,像睡著了一般油猫。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上柠偶,一...
    開封第一講書人閱讀 52,793評(píng)論 1 314
  • 那天情妖,我揣著相機(jī)與錄音,去河邊找鬼诱担。 笑死毡证,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的该肴。 我是一名探鬼主播情竹,決...
    沈念sama閱讀 41,221評(píng)論 3 423
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼匀哄!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起雏蛮,我...
    開封第一講書人閱讀 40,174評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤涎嚼,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后挑秉,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體法梯,經(jīng)...
    沈念sama閱讀 46,699評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,770評(píng)論 3 343
  • 正文 我和宋清朗相戀三年犀概,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了立哑。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,918評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡姻灶,死狀恐怖铛绰,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情产喉,我是刑警寧澤捂掰,帶...
    沈念sama閱讀 36,573評(píng)論 5 351
  • 正文 年R本政府宣布敢会,位于F島的核電站,受9級(jí)特大地震影響这嚣,放射性物質(zhì)發(fā)生泄漏鸥昏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,255評(píng)論 3 336
  • 文/蒙蒙 一姐帚、第九天 我趴在偏房一處隱蔽的房頂上張望吏垮。 院中可真熱鬧,春花似錦罐旗、人聲如沸膳汪。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,749評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)旅敷。三九已至,卻和暖如春颤霎,著一層夾襖步出監(jiān)牢的瞬間媳谁,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,862評(píng)論 1 274
  • 我被黑心中介騙來泰國(guó)打工友酱, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留晴音,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,364評(píng)論 3 379
  • 正文 我出身青樓缔杉,卻偏偏與公主長(zhǎng)得像锤躁,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子或详,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,926評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)系羞。 張土汪:刷leetcod...
    土汪閱讀 12,749評(píng)論 0 33
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn)霸琴,斷路器椒振,智...
    卡卡羅2017閱讀 134,719評(píng)論 18 139
  • You Don't Know JS: this & Object Prototypes Chapter 3: Ob...
    大橙子CZ閱讀 601評(píng)論 0 1
  • 無聊貼貼
    Dumbass閱讀 249評(píng)論 0 0
  • 生活,不知不覺的變化梧乘。 然后澎迎,不知不覺成真。 雖然选调,還有一些跟想象之中不一樣的地方夹供,只要,還想抱著這個(gè)人仁堪。哮洽。 一定...
    簡(jiǎn)墨原閱讀 142評(píng)論 0 1