元哥3天学Python--Day3

2016-09-19  本文已影响0人  kevinscake

1. Input From Keyboard

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

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
colours = ["red"]
for i in colours[:]: //用copy来for
    if i == "red":
        colours += ["black"]
    if i == "black":
        colours += ["white"]
print(colours) //['red', 'black']

4. Function

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或者return后不接数据,函数返回None

return (lub, new)

5. File management

fobj = open("ad_lesbiam.txt", "r") // r:read --> optional

fobj = open("ad_lesbiam.txt")
for line in fobj:
    print(line.rstrip())
fobj.close()
fh = open("example.txt", "w")
fh.write("To write or not to write\nthat is the question!\n")
fh.close()
with open("example.txt", "w") as fh:
    fh.write("To write or not to write\nthat is the question!\n")

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 math
from math import * //same as above, not recommanded!
from math import sin, pi
import numpy as np //rename namespace

文件名就是module名

if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

只有在run as sript时才运行,import时不运行

  • 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

通过命名前的下划线来定义。。。

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

即可以被class调用,也可以被instance调用
需要用@staticmethod指明,不需要第一个参数self

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

与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

  • 充当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())
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
上一篇 下一篇

猜你喜欢

热点阅读