type、object、class关系
type是一个类型,它的实例对象也是type。所有对象都都有类型。内置对象中比如int、float、str等 这些对象的基础类型都是type。
class Student:
pass
stu = Student()
print(type(stu))
print(Student.__bases__)
print(type(1))
print(type(int))
print(type.__bases__)
print(type(object))
print(object.__bases__)
输出
# 输出当前变量类型
<class '__main__.Student'>
# Student类的基类为object
(<class 'object'>,)
# 数字 1 的类型为int类型
<class 'int'>
# int类型其实在python中也是由一个类来表示的,它的类的类型为type类型。同样,type也是python内置的一个类
<class 'type'>
# 查看type类的基类,可以看到是object这个类
(<class 'object'>,)
# 查看object这个类的类型,可以看到是type类型
<class 'type'>
# 查看object类的基类,可以看到它是没有基类的
()
type -> class -> obj
object是最顶层的类,所有类默认继承此类(使用类名.)
魔法函数
以双下划线开始的函数,Python有很多自带的魔法函数
class Student:
def __init__(self):
self.list = ['a', 'b', 'c']
# 添加此方法,可以使实例能够for循环遍历,能够进行切片操作
def __getitem__(self, item):
return self.list[item]
stu = Student()
# 直接遍历实例
for e in stu:
print(e)
抽象基类abc模块
类似于java中的接口,无法创建实例类,继承此方法需要复写所有方法。
主要作用:
- 类型判断,使用isinstance
- 强制继承
import abc
class Cache(metaclass=abc.ABCMeta):
@abc.abstractmethod
def get(self, key):
pass
@abc.abstractmethod
def set(self, key, value):
pass
class RedisCache(Cache):
pass
# 报错: 需要实现所有的方法,才能使用,达到强制继承的作用
r = RedisCache()
isinstance方法可以判断继承关系,type不能
实例方法和静态方法
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
# 返回格式化后的数据
def get_time(self):
return '{year}-{month}-{day}'.format(year=self.year, month=self.month, day=self.day)
# 静态方法
@staticmethod
def get_format(str):
year, month, day = tuple(str.split('/'))
return Date(year, month, day)
# 类方法
# 不用指定类名去实例
@classmethod
def get_format_cls(cls, str):
# 元组解包
year, month, day = tuple(str.split('/'))
return cls(year, month, day)
d = Date.get_format_cls('2018/11/02')
print(d.get_time())
d2 = Date.get_format('2018/11/02')
print(d.get_time())
查看变量结构
- dir()方法 : 可以查看类和系统自带类型
- 类名._dict_ : 查看类属性
- 实例._dict_ : 查看实例变量
super关键字
python3之前: super(obj,self)._init_()
python3 : super()._init_()
若一个类继承了多个类,则它的调用父类方法的顺序和属性查找顺序一样(MRO)
with语句
def try_test():
try:
print('code ')
raise IndexError
return 1
except IndexError:
print('key err')
return 2
else:
# 不报错的时候会运行
print('other error')
return 3
finally:
# 都会运行
print('finally')
return 4
# return语句返回先将结果进行压栈,而后从栈顶取数据返回
使用with语句优化
# 上下文管理器协议
class Sample:
def __enter__(self):
print('enter')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('exit')
def do_something(self):
print('doing something')
with Sample() as sample:
sample.do_something()
# 输出
enter
doing something
exit
使用contexlib模块简化
import contextlib
@contextlib.contextmanager
def file_open(file_name):
print('file open ', file_name)
# 必须变成一个生成器
yield {}
print('file end')
with file_open('ccc') as f_opend:
print('file processing')
# 输出
file open ccc
file processing
file end