1. 程式人生 > >Python的程序結構[2] -> 類/class -> 類的特殊屬性

Python的程序結構[2] -> 類/class -> 類的特殊屬性

enter 字典 一個 pri 類屬性 __name__ attr ttr 定義

類的特殊屬性 / Special Property of Class


Python 中通過 class 進行類的定義,類可以實例化成實例並利用實例對方法進行調用。

類中還包含的一些共有的特殊屬性。

特殊類屬性

含義

__name__

類的名字(字符串)

__doc__

類的文檔字符串

__bases__

類的所有父類組成的元組

__dict__

類的屬性組成的字典

__module__

類所屬的模塊

__class__

類對象的類型

 1 class Foo():
 2     """
 3
This is the text that can be called by __doc__ 4 """ 5 def __init__(self): 6 self.foo = None 7 8 def foo_method(self): 9 self.foom = True 10 11 print(>>>, Foo.__name__) 12 print(>>>, Foo.__doc__) 13 print(>>>, Foo.__bases__) 14
print(>>>, Foo.__dict__) 15 print(>>>, Foo.__module__) 16 print(>>>, Foo.__class__)

上面的代碼定義了一個 Foo 類,並對類的基本特殊屬性依次進行調用,最後得到結果如下,

>>> Foo
>>> 
    This is the text that can be called by __doc__
    
>>> (<class object>,)
>>> {
__dict__: <attribute __dict__ of Foo objects>, __doc__: \n This is the text that can be called by __doc__\n , __weakref__: <attribute __weakref__ of Foo objects>, __init__: <function Foo.__init__ at 0x0301F930>, __module__: __main__, foo_method: <function Foo.foo_method at 0x0305C348>} >>> __main__ >>> <class type>

Python的程序結構[2] -> 類/class -> 類的特殊屬性