元哥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

  • 語法
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)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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