__call__方法ide
#__call__方法 class Foo: def __init__(self): print("init") def __call__(self,*args,**kwargs): print("call") obj=Foo() obj() # init # call Foo()() # init # call #對象()只執行__call__方法,很是特殊 #__init__也是,建立對象就執行__init__方法
#\__int\__方法 s="123" s=str("123") #等價 i=int(s) print(i,type(i)) #本身轉化成int類型 # 123 <class 'int'>
__int__方法code
class foo1: def __init__(self): pass def __int__(self): return 1234 def __str__(self): #用於打印,很重要,很是常見 return "haha" obj2=foo1() print(obj2,type(obj2)) #int 加上對象,執行對象的__int__方法,並將返回值賦給int對象 r=int(obj2) print(r) # <__main__.foo1 object at 0x000000FFA667AA90> <class '__main__.foo1'> # 1234
__str__方法對象
#__str__方法 class foo2: def __init__(self,name,age): self.name=name self.age=age def __str__(self): #用於打印,很重要,很是常見 return "%s-%s"%(self.name,self.age) obj3=foo2("jiaxin",10) print(obj3,type(obj3)) # jiaxin-10 <class '__main__.foo2'>