python:物件導向(類)

來源:互聯網
上載者:User

標籤:ini   訪問   utf-8   int   動態   print   工作   靜態屬性   self   

#!usr/bin/env python
# -*- coding:utf-8 -*-

__author__ = "Samson"
###類變數與執行個體變數
class Role:
n = 123#類變數,存放在類中,不存放在執行個體中,可用於節省空間的
def __init__(self, name, role, weapon, life_value = 100, money = 15000):
#建構函式
#在執行個體化時做一些類的初始化工作
self.name = name#執行個體變數(靜態屬性),存放在類中
self.role = role
self.weapon = weapon
self.life_value = life_value
self.__money = money#私人屬性,僅能在類的內部訪問

def shot(self):#類的方法,功能(動態屬性)
print("shooting...")

def got_shot(self):
print("%s:ah...,I have got shot..." %self.name)

def __show_money(self):#類的私人函數,僅能在類的內部訪問
print("money:%s" % self.__money)

def buy_gun(self, gun_name):
print("%s just bought %s" % (self.name, gun_name))

def __del__(self):#解構函式、在執行個體釋放、銷毀的時候執行的,通常用於做一些收尾工作,如關閉一些資料庫,關閉開啟的一些檔案
print("執行解構函式")

print(Role)

r1 = Role("samson", "police", "AK47")#把一個類變成一個具體對象的過程叫執行個體化
r1.got_shot()#Role.got_shot(r1)
r1.bullet_prove = True #給類添加屬性,這是可以的

r2 = Role("r2", "police", "AK47")#把一個類變成一個具體對象的過程叫執行個體化
r2.got_shot()#Role.got_shot(r1)
print(r1.weapon)
del r1.weapon#刪除屬性

r1.n = 145#相當於r1中新增了一個執行個體變數,不影響類變數
print(r1.n, r2.n)#r2中的n值不變

(未完待續)












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.