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)
原文:https://www.cnblogs.com/hell-west-road/p/11331557.html