首页 > 编程语言 > 详细

初识python魔法函数

时间:2019-08-10 16:34:03      阅读:63      评论:0      收藏:0      [点我收藏+]

python魔法函数主要是针对类

 

 1 # -*- coding: utf-8 -*-
 2 
 3 
 4 class myTest1(object):
 5     def __init__(self, argv1):
 6         ‘‘‘ myTest1 init ‘‘‘         # help()函数打印的帮助信息
 7         self.argv1 = argv1
 8 
 9     def __len__(self):
10         ‘‘‘ myTest1 length ‘‘‘
11         return len(self.argv1)
12 
13     def __str__(self):
14         ‘‘‘ myTest1 str help ‘‘‘
15         return "myTest1 __str__"
16 
17     def __repr__(self):          # __str__存在的时候,直接打印类会被覆盖
18         ‘‘‘ myTest1 repr help ‘‘‘
19         return "myTest1 __repr__"
20 
21     def __bool__(self):
22         ‘‘‘ myTest1 bool ‘‘‘
23         return isinstance(self.argv1, list)
24 
25 
26 if __name__ == "__main__":
27     run = myTest1("Hello world")
28     print(len(run))
29     print(run)
30     print(repr(run))
31     print(bool(run))
32     help(run)

输出信息:

11

myTest1 __str__

myTest1 __repr__

False

 

Help on myTest1 in module __main__ object:

 

class myTest1(builtins.object)

 |  myTest1(argv1)

 |

 |  Methods defined here:

 |

 |  __bool__(self)

 |      myTest1 bool

 |

 |  __init__(self, argv1)

 |      myTest1 init

 |

 |  __len__(self)

 |      myTest1 length

 |

 |  __repr__(self)

 |      myTest1 repr help

 |

 |  __str__(self)

 |      myTest1 str help

 |

 |  ----------------------------------------------------------------------

 |  Data descriptors defined here:

 |

 |  __dict__

 |      dictionary for instance variables (if defined)

 |

 |  __weakref__

 |      list of weak references to the object (if defined)

(END)

 

初识python魔法函数

原文:https://www.cnblogs.com/hell-west-road/p/11331557.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!