1.__doc__ 表示類的描述信息 2.__module__ 和 __class__ __module__ 表示當前操作對象在哪個模塊 __class__ 表示當前操作對象的類是什麼 3. __init__ 構造方法 通過類創建對象時,自動觸發執行 4. __del__ 析構方法 當對象在記憶體中被 ...
1.__doc__ 表示類的描述信息
class Food(object): "定義一個食物類" pass print(Food.__doc__) #輸出 定義一個食物類
2.__module__ 和 __class__
__module__ 表示當前操作對象在哪個模塊
__class__ 表示當前操作對象的類是什麼
class A(object): def __init__(self, name): self.name = name
from local.obj import A a = A('bigberg') print(a.__module__) print(a.__class__) # 輸出 local.obj # local.obj , 輸出模塊 <class 'local.obj.A'> # local.obj.A , 輸出類
3. __init__ 構造方法
通過類創建對象時,自動觸發執行
class Person(object): country = 'CN' # 公有屬性 def __init__(self, name, age, gender, province): self.name = name self.age = age self. gender = gender self.province = province p = Person('bigberg', 22, 'M', 'zhejiang')
4. __del__ 析構方法
當對象在記憶體中被釋放時,自動觸發執行,是程式自動執行的不需要人為參與
註:此方法一般無須定義,因為Python是一門高級語言,程式員在使用時無需關心記憶體的分配和釋放,因為此工作都是交給Python解釋器來執行,所以,析構函數的調用是由解釋器在進行垃圾回收時自動觸發執行的。
class Person(object): country = 'CN' def __init__(self, name, age, gender, province): self.name = name self.age = age self. gender = gender self.province = province def __del__(self): print("該對象已經被刪除!") p = Person('bigberg', 22, 'M', 'zhejiang') print(p.name) del p print(p.age) # 輸出 bigberg 該對象已經被刪除! Traceback (most recent call last): File "G:/python/untitled/study6/類的特殊成員.py", line 34, in <module> print(p.age) NameError: name 'p' is not defined
5.__dict__ 類或對象中的所有成員
把類中的成員以字典的形式列印出來

1 class Person(object): 2 3 country = 'CN' 4 5 def __init__(self, name, age, gender, province): 6 self.name = name 7 self.age = age 8 self. gender = gender 9 self.province = province 10 11 def speak(self, language): 12 print("%s mother language is %s" % (self.name, language)) 13 14 15 p = Person('bigberg', 22, 'M', 'zhejiang') 16 17 # 獲取類的成員,即:構造函數的屬性 18 print(Person.__dict__) 19 20 #輸出: {'speak': <function Person.speak at 0x0000025CCBACE510>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__doc__': None, '__init__': <function Person.__init__ at 0x0000025CCBACE488>, 'country': 'CN', '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Person' objects>} 21 22 23 # 獲取對象 p 的成員 24 print(p.__dict__) 25 26 #輸出: {'name': 'bigberg', 'province': 'zhejiang', 'gender': 'M', 'age': 22}View Code
6.__call__ 對象或類後面加括弧,觸發執行
class Person(object): def __init__(self): pass def __call__(self, *args, **kwargs): print('hello,world') p = Person() # 執行 __init__ p() # 執行 __call__ # 輸出 hello,world
7.__str__ 如果一個類中定義了__str__方法,那麼在列印 對象 時,預設輸出該方法的返回值。

1 class Person(object): 2 3 def __init__(self, name): 4 self.name = name 5 6 def __call__(self, *args, **kwargs): 7 print('hello,world') 8 9 def __str__(self): 10 return "It's a good day." 11 12 def speak(self): 13 return "%s is giving a speech." % self.name 14 15 p = Person('bigberg') 16 p.speak() 17 print(p) 18 19 #輸出 20 It's a good day.View Code