Python 程式設計入門 / Python 程式設計 - 類和物件
外觀
Python 從一開始就使用面向物件程式設計,因此建立類、使用類和物件非常容易。
class 語句建立一個新的類定義。使用者提供的類名緊跟在關鍵字 class 後面,後面跟著一個冒號,如下所示
class myclass: ‘The documentation of the class can be added here’ Class objects Class methods
class myclass:
'This docstring provides for the details of the class defined'
count=0
def __init__(self,name,paycheck):
self.name=name
self.paycheck=paycheck
myclass.count+=1
def displayworkerCount(self):
print "Total no of worker %d" %myclass.count
def displayworkerName(self):
print "Name of the user",self.name,"'s salary", self.paycheck
>>> worker1=myclass("Nobody",15000)
>>> worker2=myclass("SNGET", 10000)
>>> worker3=myclass("Somebody", 20000)
>>> worker4=myclass("Everybody",25000)
>>> worker1.count
4
>>> worker1.displayworkerCount()
Total no of worker 4
>>> worker1.displayworkerName()
Name of the user Nobody 's salary 15000
>>> print myclass.__doc__
This docstring provides for the details of the class defined
>>>
終端使用者可以使用 hasattr 物件檢查定義的類中是否定義了特定的方法或物件或例項。
>>> worker1 <__main__.myclass instance at 0x017D5990> >>> worker1.name 'Nobody' >>> worker1.paycheck 15000 >>> hasattr(worker1,'age') False >>> hasattr(worker1,'displayworkerCount') True
終端使用者可以使用以下方法隨時新增、修改、設定或刪除類和物件的屬性。
>>> worker5=myclass("","")
>>> worker5.name
''
>>> worker5.paycheck
''
>>> worker5.name="New Body"
>>> worker5.paycheck=50000
>>>
>>> worker5.name
'New Body'
>>> worker5.paycheck
50000
>>> worker1.paycheck
15000
>>> worker1.paycheck=55000
>>> worker1.paycheck
55000
>>> setattr(worker1, "paycheck", 60000)
>>> worker1.paycheck
60000
>>> >>>
>>> delattr(worker1, "name")
>>> worker1
<__main__.myclass instance at 0x0222EA80>
>>> worker1.name
Traceback (most recent call last):
File "<pyshell#372>", line 1, in <module>
worker1.name
AttributeError: myclass instance has no attribute 'name'
預設情況下,所有 Python 類都具有以下內建屬性,可以使用點運算子訪問,就像 __doc__ 屬性提供類的文件一樣。
- __dict__ : 類的名稱空間的字典
- __doc__ : 類文件字串或無,如果未定義
- __name__ : 類名
- __module__ : 定義類的模組名稱。此屬性在互動模式中為 "__main__"
- __bases__ : 一個可能為空的元組,包含基類,按照它們在基類列表中的出現順序排列。
嘗試上述方法針對上述定義的 myclass,我們得到以下結果。
>>> print "The name of the class is :", myclass.__name__
The name of the class is : myclass
>>> print "The name of the module is :", myclass.__module__
The name of the module is : __main__
>>> print "The bases for the class myclass is :", myclass.__bases__
The bases for the class myclass is : ()
>>> print "The dictionary of namespace for myclass are :",myclass.__dict__
The dictionary of namespace for myclass are : {'count': 4, '__module__': '__main__', 'displayworkerCount': <function
displayworkerCount at 0x02244B70>, 'displayworkerName': <function displayworkerName at 0x02244BB0>, '__doc__': 'This
docstring provides for the details of the class defined', '__init__': <function __init__ at 0x02244B30>}
>>> print "The document string for myclass is: ",myclass.__doc__
The document string for myclass is: This docstring provides for the details of the class defined
>>>