Python面向對象寫Student類

 直接看代碼寫法:

class Student:

   "這是Student類的說明"   #__doc__

   objCount = 0  #類的靜態變量
 
   def __init__(self, name, age):    #構造函數,創建類的實例調用
      print("構造方法!")
      self.name = name   #self代表對象
      self.__age = age   # 以__開頭私有屬性
      Student.objCount += 1


   def __del__(self):   #析構函數
         #self.__class__指向類
         Student.objCount -= 1
         print("銷燬",self.__class__.__name__, self.name)



   def Age(self):
         "這是Age的說明"
         return self.__age
 
   def Show(self):   #成員函數
      "這是Show的說明"
      print( "姓名:", self.name,  ",年齡:", self.__age)

   def __Show222(self):   #以__開頭私有成員函數
         print( "姓名:", self.name,  ",年齡:", self.__age)
 
 
   def Count(self):   #成員函數
     "這是Count的說明"
     print ("學生人數 %d" % Student.objCount)
 
 
#創建類對象
stu1 = Student("張三", 12)
print(stu1.name)
#print(stu1.__age)  #私有變量不能訪問
print(stu1.Age())
stu1.Show()
#stu1.__Show222() #私有函數不能訪問
stu1.Count()
 
 
stu2 = Student("李四", 22)
stu2.Show()
stu2.Count()


#測試對象的屬性與方法
print(hasattr(stu2, 'Show')) #測試是否有Show方法
print(hasattr(stu2, '__age'))
getattr(stu2, 'Show')()   #獲取一個方法
setattr(stu2, 'sex','男') #設置一個屬性
print(stu2.sex)


print("------------------------------------")
 
#類屬性(python內置)
print(Student.__dict__)   #類的屬性
print(Student.__name__)   #類名
print(Student.__doc__ )   #類的文檔字符串
print(Student.__module__) #類定義所在的模塊
print(Student.__bases__)  #父類組成的元組

print("------------------------------------")

help(Student)   # 查看模塊、類型、類、對象的幫助

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章