Built-in method
Any type of data will take some more or less the method of bis
Double Down method: __init__
__str__
__xxx__
In each book python species, also known as magic methods built-in methods
Features : not serious, when the call is not always a good call
example:
'abc'.split('b') # 正经调用str类型的split方法
print('abc' + 'efg') # 直观
ret = 'abc'.__add__('efg') # 不直观,不正经调用方法
print(ret)
Important way
__str__
The default print object is printed is the memory address of the object, but does not address the role defined in the class for me
__str__
method, return back, equivalent to replace the memory address of the default print object Note : A string must be return back ContentFor example, print (obj) (obj is a target), when, in fact, always invoked
obj.__str__()
, printing the return value of this methodEasy to do print (such as class annotation)
# __str__ class Course: course_lst = [] def __init__(self,name,period,price): self.name = name self.period = period self.price = price def __str__(self): return '%s,%s,%s'%(self.name,self.period,self.price) # python = Course('python','6 months',19800) # linux = Course('linux','5 months',17800) # Course.course_lst = [python,linux] # for course in Course.course_lst: # print(course) # 打印一个对象总是打印内存地址,这个数据对我们来说没有用 # 打印这个对象的时候查看这个对象的相关信息
__new__
Object instantiation process types, the program first creates a memory address, and then call
__init__
, we never cared to open up the memory space of things instantiation, because someone did help me, help us open up this memory space that__new__
methodNo objects does not matter, we can own a new
- Test case
class A: def __new__(cls,*args,**kwargs): print('执行我了') def __init__(self): print('init') self.name = 'alex' A() # 结果 # 执行我了 # 默认来说,__new__方法是替我们开辟内存空间,但是我们这里将__new__执行的改为了打印, # __init__没有内存空间,也就不会执行了 # new是没有self参数
# Introduction to Algorithms - microscopic
# 23 design patterns - Macro