程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

8、 Python learning notes - object oriented - special class members

編輯:Python
# Special class members ( Method )
"""
1、 By python Some methods defined by default
2、 These methods all have specific functions
3、 These methods all have specific ways of calling
4、 Some special class methods have default values , for example __str__、__dict__, When manually added , It is equivalent to overriding the parent class method
5、 Some special class methods have no return value, such as __setitem__、__delitem__, The calling method does not receive the return value location ( One is assignment , One is delete , Do not receive return values )
"""
class Foo:
"""
Here is the comment
"""
def __init__(self):
self.name = 'name'
pass
def __call__(self, *args, **kwargs):
return ' This is a call'
def __str__(self):
return ' This is a str'
def __int__(self):
return 10
def __len__(self):
return 20
def __add__(self, other):
return 30
def __del__(self): # destructor , Automatically execute when an object is destroyed , Delete data in memory , Reclaim memory resources
pass
def __getitem__(self, item):
return item + 10
def __setitem__(self, key, value):
print(key, value)
def __delitem__(self, key):
print(key)
def __iter__(self):
return iter([1, 2, 3])
bar = Foo() # perform __init__
print(bar()) # perform __call__, Equivalent to Foo()()
print(str(bar)) # perform __str__,
print(bar) # print(obj) It can also be called directly __str__
print(int(bar)) # perform __int__
print(len(bar)) # perform __len__
print(bar+bar) # When two objects are added, the... Of the first object is automatically executed __add__ Method , And pass the second object as a parameter
print(bar.__dict__) # __dict__ Returns all the contents encapsulated in the object in the form of a dictionary
print(Foo.__dict__) # __dict__ Return all the contents encapsulated in the class in the form of a dictionary
print(bar[1]) # perform __getitem__, take 1 Pass it to the method as a parameter
bar[2] = 22 # perform __setitem__, take 2 As key take 2 As value Pass it on to the method
del bar[3] # perform __delitem__, take 3 As key Pass it on to the method
for i in bar: # perform __iter__, Get the return value , And loop the return value .( Only those who have __iter__ It's iterative ), The return value should be an iterator
print(i)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved