[python 學習] 類

來源:互聯網
上載者:User

標籤:cte   ict   abc   其他   method   port   return   init   col   

#!/usr/bin/python# -*- encoding:utf-8 -*-class Animal:    animal_num = 0class Dog(Animal):    #類協助文檔    ‘this is help‘    #兩個底線開頭,類的私人屬性,不能在類外部存取,類內部使用self.__dog_name訪問    __Dog_name = ‘dahuang‘    dog_num = 0    #累的建構函式,初始化執行個體時調用    def __init__(self, name, color):        self.color = color        self.name = name        Dog.dog_num += 1 #類變數在內部類中調用    #self代表類的執行個體,類內部的函數必須包含且第一個參數為 self    def prt(self):        print self        print self.__class__            #self不是python關鍵字,可以使用其他代替    def prt_2(self_2):        print self_2        print self_2.__class__    def printDogName(self):        print self.name        #__private_method類的私人方法,調用self.__private_method    def __get_Dog_name(self):        return self.__Dog_name    def get_Dog_name(self):        return self.__get_Dog_name()    #輸出對象執行個體時調用(print)    #或使用str(obj)調用    def __str__(self):        return ‘print 時調用‘        #repr(obj)    def __repr__(self):        return ‘直接輸出對象,使用print列印時調用,或repr(obj)‘    # 析構方法    def __del__(self):        print ‘對象被刪除‘#執行個體化d = Dog(‘jack‘,‘red‘)#同 print dstr(d)#同 print drepr(d)#調用析構方法# del dd.prt()d.prt_2()print d.get_Dog_name() #dahuang#_foo: 以單底線開頭的表示的是 protected 類型的變數,即保護類型只能允許其本身與子類進行訪問,不能用於 from module import *#通過 object._className_attrName訪問累的私人變數print d._Dog__Dog_name #dahuang#放問類的私人方法同上print d._Dog__get_Dog_name() #dahuang #添加屬性d.age = 10#修改屬性d.age = 12# del刪除屬性del d.color#使用函數操作屬性hasattr(d,‘age‘)      #如果存在 ‘age’ 屬性返回 true getattr(d, ‘age‘)     #返回 ‘age’ 屬性的值setattr(d, ‘age‘, 13) #添加屬性 ‘age 的值為13delattr(d, ‘age‘)     #刪除屬性 ‘age‘#內建類屬性#__dict__:類的屬性#{‘__module__‘: ‘__main__‘, ‘printDogName‘: <function printDogName at 0x02B3B9B0>, # ‘prt_2‘: <function prt_2 at 0x02B3B970>, ‘prt‘: <function prt at 0x02B3B8F0>,# ‘dog_num‘: 1, ‘__doc__‘: ‘this is help‘, ‘__init__‘: <function __init__ at 0x02B3B9F0>}print Dog.__dict__ #__name__:類名#Dogprint Dog.__name__#__module__:類定義所在的模組#__main__print Dog.__module__#__bases__:類的所有父類構成的元素#(<class __main__.Animal at 0x038AABC8>,)print Dog.__bases__#列印類說明print Dog.__doc__

 

[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.