Python學習-類的基本知識

來源:互聯網
上載者:User

標籤:程式   dog   ret   col   this   eth   產生   析構   var   

#! /usr/bin/env python# -*- coding:utf-8 -*-# Author linux kuclass Dog():    def __init__(self, name):        self.name = name    def bulk(self):        print("%s : Wang wang wang!"%self.name)dog1 = Dog("dog1")dog2 = Dog("dog2")dog1.bulk()dog2.bulk()class Role(object):  #類名    n = 222    #類變數 :先找執行個體變數然後再找類變數    def __init__(self, name, role, weapon, life_value=100, money=15000, secret = "secret"):  #建構函式#建構函式,這個東西的目的,我覺得是再記憶體中開闢一個位置,相當於是給了一個銘牌號。#在執行個體化的時候做一些類的初始化的工作。#記憶體的運行是,記憶體的門牌號其實是在賦值的時候進行的,比如 r1 = Role(r1,xxx,xx),時候申請一下,然後在運行這個建構函式的時候把具體的內容傳入#運行建構函式的時候是,self是r1傳入賦予r1的值,所以self其實就是用來區分的。所以說參數self就是預留給執行個體化名稱的。        self.name = name  #執行個體變數(靜態屬性),範圍是在執行個體的本身        self.role = role        self.weapon = weapon        self.life_value = life_value        self.money = money        self.__secret = secret  #私人屬性,只能在內部的方法中可以改動#下面的函數是在類裡面的,沒有在執行個體化的地方存起來的    def shot(self): #這裡的self是執行個體化的具體名稱,標誌著地址        print("shooting...")    def got_shot(self):  #類的方法,功能(動態屬性)        print("ah...,I got shot...")    def show_secret(self):        print("The secret is %s" %self.__secret)    def __secret_method(self):  #私人方法,只能內部調用        print(self.__secret)    def show_secret_method(self):        self.__secret_method()    def buy_gun(self, gun_name):        print("just bought %s" % gun_name)    def show_all_vari(self):        print("All the vari: %s" % {self.name,self.role,self.money,self.life_value} )#解構函式:在執行個體釋放、銷毀的時候執行的,通常用於做一些收尾工作,如關閉一些資料庫連結,開啟的臨時檔案#這個函數會在程式退出的時候自動使用,也可以手動提前使用 del r1    def __del__(self):        print("end the example.%s " % self.name)        print("or do other necessary work.")r1 = Role(‘Alex‘, ‘police‘, ‘AK47‘)  #產生一個角色r1.show_all_vari()r1.got_shot()  #實際是Role.got_shot(r1)print("this is secret method:")r1.show_secret_method()print("this is secret property:")r1.show_secret()print("---------")r2 = Role(‘Jack‘, ‘terrorist‘, ‘B2‘)  #產生一個角色r2.got_shot()

 

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.