python 物件導向(二)

來源:互聯網
上載者:User

標籤:傳回值   school   property   span   color   .sh   ssm   公有   成員   

1. 成員

成員共分為三類:

1變數:

  - 執行個體變數(欄位)
    - 公有執行個體變數(欄位)
    - 私人執行個體變數(欄位)
  - 類變數(靜態欄位)
    - 公有類變數(靜態欄位)
    - 私人類變數(靜態欄位)

class Student:    school = "藍翔"       #公有的類變數    __grade = "一年級"    #私人的類變數    def __init__(self,name):        self.name = name    #公有的執行個體變數        self.__age = 18    #私人的執行個體變數stu = Student("Tom")print(stu.name)# print(stu.__age)      #私人的執行個體變數不能在類外部存取print(Student.school)# print(Student.__grade)    #私人的類變數不能在類外部存取

 

2.方法

  執行個體方法
    有個self參數


  靜態方法 : 如果方法無需使用對象中封裝的值,那麼就可以使用靜態方法

    方法上邊有@staticmethod
    參數可有可無


  類方法 : 如果在方法中會使用到當前類,那麼就用類方法

    方法上邊有@classmethod
    有個cls參數

class Student:    def __init__(self,name,age):        self.name = name        self.age = age    def dyname(self):       #執行個體方法        print(self.name)    @staticmethod    def dy(x):              #靜態方法:如果方法無需使用對象中封裝的值,那麼就可以使用靜態方法        print("哈哈哈",x)    @classmethod    def dy2(cls):           #類方法:如果在方法中會使用到當前類,那麼就用類方法        print(cls)stu = Student("Tom",18)stu.dyname()Student.dy("s15")Student.dy2()

3.屬性

  方法上有@property

  只有一個self參數 

  調用時無需加括弧 對象.方法

  對於簡單的方法,當無需傳參且有傳回值時可以使用 

class Student:    def __init__(self):        pass    @property    def shuxing(self):        return 1obj = Student()print(obj.shuxing)



2. 嵌套(建模)

 

python 物件導向(二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.