Chapter 5:对象和面向对象
两种import
方法
import random # 使用时需要加上random前缀
random.randint # <bound method Random.randint of <random.Random object at 0x10101f620>>
randint # name 'randint' is not defined
from random import randint # 可以直接使用
randint # <bound method Random.randint of <random.Random object at 0x10101f620>>
from random import * # 导入所有方法
类的定义
from UserDict import UserDict
class FileInfo(UserDict): # 创建FileInfo类并继承UserDict类
"store file metadata" # 类的docstring
def __init__(self, filename=None): #【1】
UserDict.__init__(self) #【2】
self["name"] = filename #【3】
【1】:__init__
类似构造函数,self为每一个类方法都需要指定的参数,调用时不需指定,会自动加上。
【2】:Python不会自动调用父类的构造函数,必须显式调用父类合适的方法,包括