python 面向物件-類和物件的概念和簡單使用
阿新 • • 發佈:2020-08-05
目標:
1、寫出有意義的面向物件
2、面向物件的核心(類+物件)
基礎1:
- 與變數名不同,建議類名首字母大寫,且有意義的單詞之間不要用下劃線連結,用駝峰表示。
- 類名後面是小括號(這一點和Java 很不一項),但是類的小括號裡的引數與函式值的引數是截然不同,這個引數與程序相關。
class StudentHomeWork():
基礎2:
- 定義一個最簡單的類
- 如何使用定義的這個類:與Java 不同,不需要new,這個只需要類名就可以例項化這個類,然後就可以用例項化的物件呼叫類中定義的方法
-
class Student(): name = “” age = 0 def print_file(): pass
class Student(): name = “” age = 0 def print_file(): pass student = Student() student.print_file()
基礎3:類的基本作用-封裝
#coding=utf-8 class Student(): name = "" age = 0 def print_file(self): print("name:"+self.name) print("age:"+str(self.age)) student= Student() student.name = "anson" student.print_file() # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test6.py" # name: # age:0
#coding=utf-8 class Student(): name = "" age = 0 def print_file(self): print("name:"+self.name) print("age:"+str(self.age)) student= Student() student.name = "anson" student.print_file() # Project/python_ToolCodes/test6.py" # name:anson # age:0
- 建議將類封裝成一個.py檔案,但是將類的呼叫放在另外一個檔案中
from test6 import Student student = Student() student.name = "anson" student.print_file()
基礎4:類->物件以及物件的行為--寫出有意義的類
student的行為是寫作業,印表機的行為才是列印
#coding=utf-8 class Student(): name = "" age = 0 def do_homework(self): print(self.name +"do homework") class Printer(): def print_file(self): print("name:"+self.name) print("age:"+str(self.age))