元哥3天学Python--Day3

1. Input From Keyboard

  • input() ---> raw data as string
  • eval() ---> inpute gets evaluated

会根据输入的格式来转换相应的数据类型

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后不接数据,函数返回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来自动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()
  • 设置当前读写位置

.seek(i) --> 移到 ith byte
.tell() --> 当前位置
.read(i) --> 从当前位置向后读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时才运行,import时不运行

  • Package
  • It's possible to put several modules into a Package.
  • 在包含多个.py文件的文件夹下建一个__init__.py文件
from SimplePackage import a, b //包含a.py  b.py
import SimplePackage //错误!

7. Obeject-Oriented Programming

everything is a class in Python

class Robot:
    pass
  1. Attributes

储存在instance的一个dict里面__dict__

  1. Method

第一个参数要是self

  1. __init__ Method

对象创建时执行的初始化

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__ --> 能够让对象被str()使用,但返回结果不可通过eval()转回对象

  • __repr__ -->能够让对象被repr()使用,且返回结果可通过eval()转回对象

  • 当只有__str__定义时,str()可用但repr()不可用;当只有__repr__定义时,两个均可用

  • 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调用,也可以被instance调用
需要用@staticmethod指明,不需要第一个参数self

class Robot:
    __counter = 0
    
    def __init__(self):
        type(self).__counter += 1
        
    @staticmethod
    def RobotInstances():
        return Robot.__counter
  • Class Method

与Static Method的相同点:即可以被class调用,也可以被instance调用
不同点:第一个参数是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
  • 充当getter & setter的角色
  • 无getter & setter的情况下又能实现他们的功能
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
  • 使用情况
  • 如果某个attr需要被user使用,则设计为public并定义它对应的property
  • 如果不需要被user使用,则设计为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 -->对继承下来的方法进行新的定义

    但是方法名,参数,返回值类型保持不变

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容