[ICS_32A] Lecture1Week4

模块导入 Module Import

#powers.py
def square(n):
    return n*n
def cube(n):
    return n**3

#program.py
import powers
def ask_for_number():
    return int(input())
def run_user_interface():
    number=ask_for_number()
    squared=powers.square(number)
    cubed=powers.cube(number)
    print(f'The square of {number} is {squared}')
    print(f'The cube of {number} is {cubed}')

run_user_interface()
  1. Python的模块名不能重,不要把自己的模块命名成math.py之类的
  2. Executable module 对比 module that provide tools

    some_else.py

    def something():
        number=program.ask_for_number() =》出错
  3. import x 实质上是让Shell直接把x.py执行一遍,所以全局语句也会被执行
  4. 这也就是为什么要用
    if name == "main":
  5. 更改后的program.py

    program.py

    import powers
    def ask_for_number():
        return int(input())
    def run_user_interface():
        number=ask_for_number()
        squared=powers.square(number)
        cubed=powers.cube(number)
        print(f'The square of {number} is {squared}')
        print(f'The cube of {number} is {cubed}')
    if __name__ =="__main__":
        run_user_interface()

    Network

  6. Socket: one end of a network "conversation"
    "connecting" a socket means establishing a connection between sockets in two programs.
  7. A socket contains two streams:
    1. input stream
    2. output stream
  8. client and server:
    1. client is the one that initiates the conversation
    2. server is the one that accepts the request and responds to it
  9. IP = Internet Protocol
    choose你想要连接的machine
  10. IP要考
  11. IP : four numbers in the range 0-255, 中间由.分割
    256=2^8
  12. port端口:0-65535
    65536=2^16
  13. 一些特殊的IP:127.0.0.1 一般指本机
  14. DNS(Domain name service)
    maps "fully-qualified domain names"域名 into IP addresses
  15. import socket
  16. socket.socket是socket里的一种type
  17. example_socket=socket.socket()
  18. example.connect((IP adress,port)) -> 要是一个(IP,port)的tuple
  19. 如果连接一个不存在的地址,会出错 getaddrinfo failed之类的
  20. 要创建pseudo files来处理IO streams
    input_stream=example_socket.makefile('r')
    output_stream=example_socket,makefile('w')