0%

Python学习笔记02

资料:廖雪峰Python教程

IDE:Spyder

类和实例

  1. class后的Student是类:

    1
    2
    3
    4
    5
    6
    7
    8
    class Student(object):

    def __init__(self, name, score):
    self.name = name
    self.score = score

    def print_score(self):
    print('%s: %s' % (self.name, self.score))

    __init__为类初始化了两个属性:namescore

    print_score为类定义了一个方法

    self为创建的实例本身,MATLAB定义类时使用的objself的功能类似

  2. 变量bart是指向Student的一个实例:

    1
    2
    bart = Student('Bart Simpson', 59)
    bart.print_score()

限制访问

  1. 实例的变量名如果以__开头,就变成了一个私有变量(private):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class Student(object):

    def __init__(self, name, score):
    self.__name = name
    self.__score = score

    def print_score(self):
    print('%s: %s' % (self.__name, self.__score))

    def get_name(self):
    return self.__name
  2. __name__score为私有变量,外部无法访问,但可通过_Student__name来访问__name变量:

    1
    2
    3
    bart = Student('Bart Simpson', 59)  # 构造实例
    bart.__name # 报错: AttributeError
    bart._Student__name # 不建议使用
  3. 错误做法:

    1
    2
    bart.__name = 'New Name'
    bart.__name # 输出'New Name'

    内部的__name变量已经被Python解释器自动改成了_Student__name,而外部代码给bart新增了一个__name变量。用get_name检验:

    1
    bart.get_name() # get_name()内部返回self.__name

继承和多态

  1. 定义一个class的时候,可以从某个现有的class继承,新的class称为\(\stackrel{\mathrm{Subclass}}{\text{子类}}\),而被继承的class称为\(\stackrel{\mathrm{Base~class}}{\text{父类}}\)\(\stackrel{\mathrm{Super~class}}{\text{超类}}\)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    class Animal(object):
    def run(self):
    print('Animal is running...')

    def eat(self):
    print('Animal is eating...')


    class Dog(Animal):

    def eat(self):
    print('Dog is eating...')


    dog = Dog()
    dog.run() # Animal is running...
    dog.eat() # Dog is eating...
  2. 我们定义的数据类型和Python自带的数据类型,比如str、list、dict没什么两样:

    1
    2
    3
    a = list() # a是list类型
    b = Animal() # b是Animal类型
    c = Dog() # c是Dog类型

    可用isinstance()判断变量类型:

    1
    2
    3
    4
    isinstance(a, list)  # True
    isinstance(b, Animal) # True
    isinstance(c, Dog) # True
    isinstance(c, Animal) # True

获取对象信息

  1. type()

    1
    2
    3
    4
    5
    6
    7
    type(123)  # <class 'int'>
    type(123)==int # True

    type('str') # <class 'str'>
    type('abc')==str # True

    type(abs) # <class 'builtin_function_or_method'>

    使用types模块判断是否为函数:

    1
    2
    3
    4
    5
    6
    7
    8
    import types
    def fn():
    pass

    type(fn)==types.FunctionType # True
    type(abs)==types.BuiltinFunctionType # True
    type(lambda x: x)==types.LambdaType # True
    type((x for x in range(10)))==types.GeneratorType # True
  2. isinstance()

    继承和多态中已有示例。补充判断一个变量是否是某些类型中的一种:

    1
    2
    isinstance([1, 2, 3], (list, tuple))  # True
    isinstance((1, 2, 3), (list, tuple)) # True
  3. dir()

    返回一个包含字符串的list,获得对象的所有属性和方法。

    getattr()setattr()以及hasattr(),可以直接操作一个对象的状态:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class MyObject(object):
    def __init__(self):
    self.x = 9

    def power(self):
    return self.x * self.x

    obj = MyObject()
    hasattr(obj, 'x') # 有属性'x'吗?
    setattr(obj, 'y', 19) # 设置一个属性'y'
    getattr(obj, 'y') # 获取属性'y'

实例属性和类属性

1
2
3
4
5
6
7
8
9
class Student(object):
NAME = 'STUDENT'
def __init__(self, name):
self.name = name

s = Student('Bob') # 实例属性
s.score = 90 # 添加实例属性
s.name # 实例属性
s.NAME # 类属性

错误处理

Python内置了try...except...finally...的错误处理机制:

1
2
3
4
5
6
7
8
9
10
11
12
try:
x = float(input('输入第一个数: '))
y = float(input('输入第二个数: '))
print(x / y)
except ZeroDivisionError:
print('分母不等为0!')
except ValueError:
print('输入应为数!')
else:
print('没问题')
finally:
print(x, y)

常见错误类:

类名 描述
Exception 几乎所有错误类都是从它派生而来的
OSError 操作系统不能执行指定的任务(如打开文件)时引发
IndexError 使用序列中不存在的索引时引发
KeyError 使用映射中不存在的键值时引发
NameError 找不到变量时引发
SyntaxError 代码不正确时引发
TypeError 将内置操作或函数用于类型不正确的对象时引发
ValueError 将内置操作或函数用于值不正确的对象时引发
ZeroDivisionError 在除法或求模运算的第二个参数为零时引发

更多错误详见:Exception hierarchy