1. 程式人生 > >Python面向對象-學習筆記

Python面向對象-學習筆記

變量 如果 display pytho 返回 pri splay one 對象

技術分享圖片
1 class Student():
2     name = lemon
3 
4 print(Student.__dict__)
5 print(Student.name)
6 Student.name = lemon-Xu
7 print(Student.name)
創建一個類,並訪問屬性
  • Class.__dict__:返回類相關信息
  • Class.name:設置或返回屬性
技術分享圖片
 1 class Student():
 2     name = lemon
 3 
 4     def say(self,name):
 5         self.name = name
6 print(self.name) 7 8 9 a = Student() 10 11 a.say(lemon-Xu) 12 13 Student.say(Student,lemon-X)
類函數
  • 類函數第一個參數必須傳入一個對象
  • 當實例化對象調用時傳入自身.如果類對象調用時必須手動傳入類對象
技術分享圖片
 1 class Student():
 2     name = lemon
 3 
 4     def __init__(self,name):
 5         self.name = name
 6 
 7 
 8 a = Student(
lemon-Xu) 9 b = Student(lemon-a) 10 11 print(a.__dict__) 12 print(b.__dict__) 13 print(Student.__dict__)
構造__init__
  • __init__(self),建議只寫一個,重載請參考:https://www.cnblogs.com/erbaodabao0611/p/7490439.html
技術分享圖片
 1 class Student():
 2     __name = lemon
 3 
 4     def __init__(self,name):
 5         self.__name
= name 6 a = Student(lemon-X) 7 try: 8 print(a.name) 9 except : 10 print(雙下滑線的變量名被更名,所以找不到它,它被改名為_Class__attribute) 11 print(a._Student__name) 12 13 print(Student._Student__name)
private,__name
  • 被__(雙下劃線)修飾的屬性,會被更名為_Class__attribute

Python面向對象-學習筆記