python从入门到坚持
一.特殊属性
1.特殊属性
魔术方法名称 | 功能 |
---|---|
__name__ | 类、函数、方法等的名字 |
__module__ | 类定义所在的模块 |
__class__ | 对象或类所属的类 |
__bases__ | 当前类的基类(父类) |
__doc__ | 类、函数的文档帮助,没有定义为None |
__mro__ | Method Resolution Order 方法解析顺序 |
__dict__ | 类或实例的属性,可写的字典 |
2.查看属性
__dir__
:返回类或者对象的所有成员名称列表。dir()函数就是调用__dir__
( )。
(1)如果dir([obj])参数obj包含方法__dir__
( ),该方法被调用。
(2)如果Obj不包含__dir__
( ),该方法将最大限度收集属性信息
dir(obj)对于不同类型的对象obj具有不同的行为:
(1)如果对象是模块对象,返回的列表包含模块的属性名和变量名;
(2)如果对象是类型或者类对象,返回的列表包含类的属性名,及它的基类的属性名;
(3)如果obj不写,即dir( ),返回列表包含内容不同;
-
在模块中,返回模块的属性和变量名
-
在函数中,返回本地作用域的变量名
-
在方法中,返回本地作用域的变量名
二.创建,初始化与销毁
1.创建,初始化与销毁
class Student(object):
def __new__(cls, name):
print('正在new.....')
# 不知道new方法试药干吗的, 直接返回父类的new方法
return super(Student, cls).__new__(cls)
# 初始化(构造)方法: 创建对象时自动执行
def __init__(self, name):
print("正在初始化对象.....")
self.name = name
# 析构方法: 对象删除时自动调用
def __del__(self):
print("正在删除对象.....")
# 当程序运行结束之后, 会自动释放变量信息. 会自动调用析构方法;
s = Student('westos')
print(s.name)
2.python__new__
,__init__
,__del__
的区别?
(1)new的功能是在生成对象之前所做的动作,接受的参数是cls类,负责对象的创建
(2)init是对象在生成之后完善对象的属性,它接受的是self对象,负责对象的初始化
(3)对象生成是在new里面return(返回一个对象)
三.可视化
1.可视化
from datetime import date
d = date(2019, 10, 10)
print(d.year)
print(d.month)
print(d)
class Student(object):
# 初始化(构造)方法: 创建对象时自动执行
def __init__(self, name):
print("正在初始化对象.....")
self.name = name
# 如果没有__str__, 自动返回__repr__的内容
# 对象的字符串打印
def __str__(self):
return "<Student: %s>" %(self.name)
# 在交互式python环境中产生作用
def __repr__(self):
return self.name
s = Student("westos")
print(s)
类型判断要使用type或isinstance,不能通过判断print输出是否带引号来判断输出值的类型。
(1)str()与repr()都是python中的内置函数,是直接用来格式化字符串的函数。
(2)而__str__
与__repr__
是在类(对象)中对类(对象)本身进行字符串处理。
四.类型转换
1.类型转换
五.索引与切片
1.索引与切片
class Student(object):
# 函数的默认值必须是不可变数据类型
def __init__(self, name, scores=(100, 60)):
self.name = name
self.scores = list(scores)
# 索引的时候, 是对成绩进行索引/切片的;
def __getitem__(self, index):
# print(index)
# 如果是查看索引, 传递的index是索引值;
# 如果是切片, index是slice对象;
return self.scores[index]
# 对指定索引index修改值; s[0] = 89 ====> index=0, value=89
def __setitem__(self, index, value):
self.scores[index] = value
def __delitem__(self, index):
del self.scores[index]
liming = Student('liming', [100, 89, 100])
索引
(1)索引值的获取
print(liming[0])
print(liming[1])
print(liming[2])
(2)索引值的重新赋值
liming[0] = 90
print(liming[0])
(3)删除索引值
del liming[0]
print(liming[:2])
切片
(1)切片值的获取
print(liming[:2])
print(liming[-2]:)
(2)切片值的重新赋值
liming[:2] = [10, 10]
print(liming.scores)
(3)删除切片值
del liming[:2]
print(liming.scores)
六.重复、连接与成员操作符
del __mul__(self, other):
#(4)实现*的效果,具体返回什么取决于代码的业务需求
"""对于学生的每一门成绩乘3"""
return [i*other for i in self.scores]
#(4)判断是否可以重复?
print(liming * 3)
del __add__(self, other):
#(5)连接的时候必须是同一种数据类型
"""将两个学生的成绩拼接"""
return self.scores + other.scores
#(5)连接?
aohong = Student('小红', [100, 90, 90])
print(xiaohong + liming)
def __contains__(self, item):
#(6)判断某个元素是否存在于这个对象中?
return item in self.scores
#(6)成员操作符?判断是否在对象里面存在?
print(100 in xiaohong)
print(101 in xiaohong)
print(101 not in xiaohong)
七.循环
def __iter__(self): #迭代,使得该对象可以实现for循环
#将列表转换为迭代的类型,可以for循环,一定要返回iter类型的数据;
return iter(self.scores)
#实现for循环
for item in liming:
print(item)
八.with语句安全上下文
class Myopen(object):
def __init__(self, name, mode = 'r')
self.name = name
self.mode = mode
def __enter__(self):
#当with语句进入并开始执行时,执行的内容,需要返回一个对象,在执行结束之后用来关闭或者其他操作
self.f = open(self.name, self.mode)
print('正在打开文件%s......' %(self.name))
return self.f
def __exit__(self, exc_type, exc_val, exc_tb):
self.f.close()
print('文件正在关闭......')
with Myopen('/tmp/passwd') as f:
print(f.read())
九.魔术方法汇总
基本的魔法方法
__new__(cls[, ...])
1. __new__ 是在一个对象实例化的时候所调用的第一个方法
2. 它的第一个参数是这个类,其他的参数是用来直接传递给 __init__ 方法
3. __new__ 决定是否要使用该 __init__ 方法,因为 __new__ 可以调用其他类的构造方法或者直接返回别的实例对象来作为本类的实例,如果 __new__ 没有返回实例对象,则 __init__ 不会被调用
4. __new__ 主要是用于继承一个不可变的类型比如一个 tuple 或者 string
__init__(self[, ...])
构造器,当一个实例被创建的时候调用的初始化方法
__del__(self)
析构器,当一个实例被销毁的时候调用的方法
__call__(self[, args...])
允许一个类的实例像函数一样被调用:x(a, b) 调用 x.__call__(a, b)
__len__(self)
定义当被 len() 调用时的行为
__repr__(self)
定义当被 repr() 调用或者直接执行对象时的行为
__str__(self)
定义当被 str() 调用或者打印对象时的行为
__bytes__(self)
定义当被 bytes() 调用时的行为
__hash__(self)
定义当被 hash() 调用时的行为
__bool__(self)
定义当被 bool() 调用时的行为,应该返回 True 或 False
__format__(self, format_spec)
定义当被 format() 调用时的行为
有关属性
__getattr__(self, name) 定义当用户试图获取一个不存在的属性时的行为
__getattribute__(self, name) 定义当该类的属性被访问时的行为
__setattr__(self, name, value) 定义当一个属性被设置时的行为
__delattr__(self, name) 定义当一个属性被删除时的行为
__dir__(self) 定义当 dir() 被调用时的行为
__get__(self, instance, owner) 定义当描述符的值被取得时的行为
__set__(self, instance, value) 定义当描述符的值被改变时的行为
__delete__(self, instance) 定义当描述符的值被删除时的行为
比较操作符
__lt__(self, other) 定义小于号的行为:x < y 调用 x.__lt__(y)
__le__(self, other) 定义小于等于号的行为:x <= y 调用 x.__le__(y)
__eq__(self, other) 定义等于号的行为:x == y 调用 x.__eq__(y)
__ne__(self, other) 定义不等号的行为:x != y 调用 x.__ne__(y)
__gt__(self, other) 定义大于号的行为:x > y 调用 x.__gt__(y)
__ge__(self, other) 定义大于等于号的行为:x >= y 调用 x.__ge__(y)
算数运算符
__add__(self, other) 定义加法的行为:+
__sub__(self, other) 定义减法的行为:-
__mul__(self, other) 定义乘法的行为:*
__truediv__(self, other) 定义真除法的行为:/
__floordiv__(self, other) 定义整数除法的行为://
__mod__(self, other) 定义取模算法的行为:%
__divmod__(self, other) 定义当被 divmod() 调用时的行为
__pow__(self, other[, modulo]) 定义当被 power() 调用或 ** 运算时的行为
__lshift__(self, other) 定义按位左移位的行为:<<
__rshift__(self, other) 定义按位右移位的行为:>>
__and__(self, other) 定义按位与操作的行为:&
__xor__(self, other) 定义按位异或操作的行为:^
__or__(self, other) 定义按位或操作的行为:|
反运算
__radd__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rsub__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rmul__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rtruediv__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rfloordiv__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rmod__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rdivmod__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rpow__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rlshift__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rrshift__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rand__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rxor__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__ror__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
增量赋值运算
__iadd__(self, other) 定义赋值加法的行为:+=
__isub__(self, other) 定义赋值减法的行为:-=
__imul__(self, other) 定义赋值乘法的行为:*=
__itruediv__(self, other) 定义赋值真除法的行为:/=
__ifloordiv__(self, other) 定义赋值整数除法的行为://=
__imod__(self, other) 定义赋值取模算法的行为:%=
__ipow__(self, other[, modulo]) 定义赋值幂运算的行为:**=
__ilshift__(self, other) 定义赋值按位左移位的行为:<<=
__irshift__(self, other) 定义赋值按位右移位的行为:>>=
__iand__(self, other) 定义赋值按位与操作的行为:&=
__ixor__(self, other) 定义赋值按位异或操作的行为:^=
__ior__(self, other) 定义赋值按位或操作的行为:|=
一元操作符
__pos__(self) 定义正号的行为:+x
__neg__(self) 定义负号的行为:-x
__abs__(self) 定义当被 abs() 调用时的行为
__invert__(self) 定义按位求反的行为:~x
类型转换
__complex__(self) 定义当被 complex() 调用时的行为(需要返回恰当的值)
__int__(self) 定义当被 int() 调用时的行为(需要返回恰当的值)
__float__(self) 定义当被 float() 调用时的行为(需要返回恰当的值)
__round__(self[, n]) 定义当被 round() 调用时的行为(需要返回恰当的值)
__index__(self)
1. 当对象是被应用在切片表达式中时,实现整形强制转换
2. 如果你定义了一个可能在切片时用到的定制的数值型,你应该定义 __index__
3. 如果 __index__ 被定义,则 __int__ 也需要被定义,且返回相同的值
上下文管理(with 语句)
__enter__(self)
1. 定义当使用 with 语句时的初始化行为
2. __enter__ 的返回值被 with 语句的目标或者 as 后的名字绑定
__exit__(self, exc_type, exc_value, traceback)
1. 定义当一个代码块被执行或者终止后上下文管理器应该做什么
2. 一般被用来处理异常,清除工作或者做一些代码块执行完毕之后的日常工作
容器类型
__len__(self) 定义当被 len() 调用时的行为(返回容器中元素的个数)
__getitem__(self, key) 定义获取容器中指定元素的行为,相当于 self[key]
__setitem__(self, key, value) 定义设置容器中指定元素的行为,相当于 self[key] = value
__delitem__(self, key) 定义删除容器中指定元素的行为,相当于 del self[key]
__iter__(self) 定义当迭代容器中的元素的行为
__reversed__(self) 定义当被 reversed() 调用时的行为
__contains__(self, item) 定义当使用成员测试运算符(in 或 not in)时的行为