python3 自定制format格式化,很多很多的内置方法。。。。。。。。。。。

1.哈哈哈,说实话,前面的foamat格式化并不是很懂:

  举例:

 1 date_format={
 2     "y-m-d":"{0.year}年{0.month}月{0.day}日",
 3     "y:m:d":"{0.year}:{0.month}:{0.day}"
 4 }
 5 class Date():
 6     def __init__(self,year,month,day):
 7         self.year=year
 8         self.month=month
 9         self.day=day
10     def __format__(self, format_spec):
11         if not format_spec or format_spec not in date_format:
12             return "请重新输入正确的日期格式"
13         else:
14             fm=date_format[format_spec]
15             return fm.format(self)
16 d=Date(2018,9,26)
17 print(format(d,"y:m:d"))
18 print(format(d,"y-m-d"))
19 print(format(d,"qwe"))
20 
21 
22 
23 #############
24 2018:9:26
25 2018年9月26日
26 请重新输入正确的日期格式
View Code

 2.__slots__

  作用:定义__slots__后,__slots__就会为实例使用一种更加紧凑的内部表示。实例通过一个很小的固定大小的数组来构建,而不是为每个实例定义一个字典,这跟元组或列表很类似。在__slots__中列出的属性名在内部被映射到这个数组的指定小标上。使用__slots__一个不好的地方就是不能再给实例添加新的属性了,只能使用在__slots__中定义的那些属性名。定义了__slots__后的类不再 支持一些普通类特性了,比如多继承。大多数情况下,应该只在那些经常被使用到 的用作数据结构的类上定义__slots__比如在程序中需要创建某个类的几百万个实例对象 。

  关于__slots__的一个常见误区是它可以作为一个封装工具来防止用户给实例增加新的属性。尽管使用__slots__可以达到这样的目的,但是这个并不是它的初衷。更多的是用来作为一个内存优化工具。

举例:定义它了之后,就没有属性字典了(报错)。
 1 class Aa():
 2     _slots__=__slots__=['name','age']  #就是等于{'name':None,'age':None}
 3     print("啦啊啊啊啊啊啊啊啦啦啦,是时候表演真正的技术了")
 4 a=Aa()
 5 print(a.__dict__)
 6 
 7 ############
 8 
 9 啦啊啊啊啊啊啊啊啦啦啦,是时候表演真正的技术了
10 Traceback (most recent call last):
11   File "E:/Python/_demo/_demo1.py", line 560, in <module>
12     print(a.__dict__)
13 AttributeError: 'Aa' object has no attribute '__dict__'
View Code
 1 class Aa():
 2     _slots__=__slots__=['name','age']  #就是等于{'name':None,'age':None}
 3     print("啦啊啊啊啊啊啊啊啦啦啦,是时候表演真正的技术了")
 4 a=Aa()
 5 a.name="小猪猪"
 6 a.age=18
 7 print(a.name)
 8 print(a.age)
 9 print(Aa.__slots__)
10 print(a.__slots__)
11 
12 ################
13 
14 啦啊啊啊啊啊啊啊啦啦啦,是时候表演真正的技术了
15 小猪猪
16 18
17 ['name', 'age']
18 ['name', 'age']
View Code

 赋值其中没有定义的属性报错:

 1 class Aa():
 2     _slots__=__slots__=['name','age']  #就是等于{'name':None,'age':None}
 3     print("啦啊啊啊啊啊啊啊啦啦啦,是时候表演真正的技术了")
 4 a=Aa()
 5 a.gender=""
 6 print(a.gender)
 7 print(Aa.__slots__)
 8 print(a.__slots__)
 9 
10 #################
11 啦啊啊啊啊啊啊啊啦啦啦,是时候表演真正的技术了
12 Traceback (most recent call last):
13   File "E:/Python/_demo/_demo1.py", line 560, in <module>
14     a.gender=""
15 AttributeError: 'Aa' object has no attribute 'gender'
View Code

3.__doc__

描述信息:不能被继承

 1 class Aa():
 2     '我是描述信息'
 3     print(">>>>>>>>>>>>>>>>>>>>>>")
 4 class Bb(Aa):
 5     print("<<<<<<<<<<<<<<<<<<<<<<<<<")
 6 a=Aa()
 7 b=Bb()
 8 print(a.__doc__)
 9 print(b.__doc__)#不能被继承
10 
11 
12 #########
13 >>>>>>>>>>>>>>>>>>>>>>
14 <<<<<<<<<<<<<<<<<<<<<<<<<
15 我是描述信息
16 None
View Code

 4.

  __module__ 表示当前操作的对象在那个模块

  __class__     表示当前操作的对象的类是什么

 1 from demo3.demo2 import C
 2 
 3 c=C()
 4 print(c.__module__)
 5 print(c.__class__)
 6 
 7 
 8 ########
 9 demo3.demo2
10 <class 'demo3.demo2.C'>
View Code

 5.__call__

对象后面加括号,触发执行。

注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()

 1 class Foo:
 2 
 3     def __init__(self):
 4         pass
 5 
 6     def __call__(self, *args, **kwargs):
 7 
 8         print('__call__')
 9 
10 
11 obj = Foo() # 执行 __init__
12 obj()       # 执行 __call__
13 
14 
15 ###############
16 __call__
View Code

6.

__next__和__iter__实现迭代器协议

 1 class Foo:
 2     def __init__(self,n):
 3         self.n=n
 4     def __iter__(self):
 5         return self
 6 
 7     def __next__(self):
 8         if self.n == 13:
 9             raise StopIteration('终止了')
10         self.n+=1
11         return self.n
12 
13 f1=Foo(10)
14 
15 for i in f1:  # obj=iter(f1)------------>f1.__iter__()
16      print(i)  #obj.__next_()
17 
18 ####################
19 11
20 12
21 13
View Code

7. 描述符(__get__,__set__,__delete__)

(1)描述符是什么:描述符本质就是一个新式类,在这个新式类中,至少实现了__get__(),__set__(),__delete__()中的一个,这也被称为描述符协议.
__get__():调用一个属性时,触发
__set__():为一个属性赋值时,触发
__delete__():采用del删除属性时,触发

包含这三个方法的新式类称为描述符,由这个类产生的实例进行属性的调用/赋值/删除,并不会触发这三个方法
1 #####定义一个描述符
2 class Aoo():
3     def __get__(self, instance, owner):
4         print("执行__get__方法啦")
5     def __set__(self, instance, value):
6         print("执行__set__方法啦")
7     def __delete__(self, instance):
8         print("执行__delete__方法啦")
View Code

(2)描述符的作用:是用来代理另外一个类的属性的(必须把描述符定义成这个类的类属性,不能定义到构造函数中)

 1 #####定义一个描述符
 2 class Aoo():
 3     def __get__(self, instance, owner):
 4         print("执行__get__方法啦")
 5     def __set__(self, instance, value):
 6         print("执行__set__方法啦")
 7     def __delete__(self, instance):
 8         print("执行__delete__方法啦")
 9 
10 class Boo():
11     i=Aoo()##################定义到类属性里面喔
12     def __init__(self,n):
13         self.i=n
View Code

(3)描述符分两种
一 数据描述符:至少实现了__get__()和__set__()

 非数据描述符:没有实现__set__()

(4)注意事项:
一 描述符本身应该定义成新式类,被代理的类也应该是新式类
二 必须把描述符定义成这个类的类属性,不能为定义到构造函数中
三 要严格遵循该优先级,优先级由高到底分别是
1.类属性
2.数据描述符
3.实例属性
4.非数据描述符
5.找不到的属性触发__getattr__()

此处差个示例:

啦啦啦啦啦啦啦

7.__enter__和__exit__

   (1)上下文管理协议,即with语句,为了让一个对象兼容with语句,必须在这个对象的类中声明__enter__和__exit__方法

1 # with open("a.txt","rb") as f:
2 #     pass
3 # # open("a.txt","rb")这个就是类似于实例化一个对象,
4 # # as f对象重新命名为f
View Code
(2)没有异常的情况下,整个代码块运行完毕后去触发__exit__,它的三个参数都为None
 1 class Aa():
 2     def __init__(self,name):
 3         self.name=name
 4     def __enter__(self):
 5         print("__enter__执行了")
 6     def __exit__(self, exc_type, exc_val, exc_tb):
 7         print("啦啦啦,被我打败了")
 8         print(exc_type)
 9         print(exc_val)
10         print(exc_tb)
11 with Aa("a.txt") as f:
12     print(f)
13 
14 
15 
16 ###################
17 __enter__执行了
18 None
19 啦啦啦,被我打败了
20 None
21 None
22 None
View Code

 (3)有异常的情况下,从异常出现的位置直接触发__exit__

     如果__exit__的返回值为True,代表吞掉了异常(不会出现报错)
     __exit__的的运行完毕就代表了整个with语句的执行完毕
 1 class Aa():
 2     def __init__(self,name):
 3         self.name=name
 4     def __enter__(self):
 5         print("__enter__执行了")
 6     def __exit__(self, exc_type, exc_val, exc_tb):
 7         print("啦啦啦,被我打败了")
 8         # print(exc_type)
 9         # print(exc_val)
10         # print(exc_tb)
11         return True
12 with Aa("a.txt") as f:
13     print("》》》》》》》》")
14     print(f.name)
15 
16 #################
17 __enter__执行了
18 》》》》》》》》
19 啦啦啦,被我打败了
View Code

 (4)有异常的情况下,从异常出现的位置直接触发__exit__

              如果__exit__的返回值不为True,代表吐出了异常

      __exit__的的运行完毕就代表了整个with语句的执行完毕
 1 class Aa():
 2     def __init__(self,name):
 3         self.name=name
 4     def __enter__(self):
 5         print("__enter__执行了")
 6     def __exit__(self, exc_type, exc_val, exc_tb):
 7         print("啦啦啦,被我打败了")
 8         # print(exc_type)
 9         # print(exc_val)
10         # print(exc_tb)
11         return False###简单粗暴,直接为false
12 with Aa("a.txt") as f:
13     print("》》》》》》》》")
14     print(f.name)
15 
16 ##################
17 Traceback (most recent call last):
18   File "E:/Python/_demo/_demo1.py", line 612, in <module>
19     print(f.name)
20 AttributeError: 'NoneType' object has no attribute 'name'
21 __enter__执行了
22 》》》》》》》》
23 啦啦啦,被我打败了
View Code
__exit__的的运行完毕就代表了整个with语句的执行完毕,后面的代码则不会运行了。
 1 class Aa():
 2     def __init__(self,name):
 3         self.name=name
 4     def __enter__(self):
 5         print("__enter__执行了")
 6     def __exit__(self, exc_type, exc_val, exc_tb):
 7         print("啦啦啦,被我打败了")
 8         # print(exc_type)
 9         # print(exc_val)
10         # print(exc_tb)
11         return False###简单粗暴,直接为false
12 with Aa("a.txt") as f:
13     print("》》》》》》》》")
14     print(f.name)
15     print("》》》》》》》》》》????????")
16     print("》》》》》》》》》》。。")
17     print("》》》》》》》》》》????????")
18     print("》》》》》》》》》》。。")
19 
20 ########################################
21 __enter__执行了
22 》》》》》》》》
23 啦啦啦,被我打败了
24 Traceback (most recent call last):
25   File "E:/Python/_demo/_demo1.py", line 612, in <module>
26     print(f.name)
27 AttributeError: 'NoneType' object has no attribute 'name'
View Code
posted @ 2018-09-25 23:39  小猪猪猪  阅读(645)  评论(0)    收藏  举报