1. 程式人生 > >Python 面向對象3

Python 面向對象3

生成 clas 實例對象 aos pri self. 抽象 屬性 elf

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 作者:Presley
# 郵箱:[email protected]
# 時間:2018-08-05
# OOP學習1

class Role(object):
members = 0
ac = None
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
self.aaa = 1
Role.members += 1#每增加一個實例則members值加1
def shot(self):
print("shooting...")

def got_shot(self):
print("ah...,I got shot...")

def buy_gun(self,gun_name):
print("just bought {0}".format(gun_name))
self.gun_name = gun_name
print(self.aaa)
print(self.ac)

#在沒有實例化之前是不能調實例化中的屬性的但是可以掉用類中的屬性
print(Role.ac)#能打印
#print(Role.weapon)#報錯,顯示沒有weapon,因為沒有實例化


#Role的實例
#把一個抽象的類變成一個具體的對象的過程
r1 = Role("wohaoshuai1","police","AK47")#生成一個角色
#相當於Role(p1,"wohaoshuai","police","AK47")

r2 = Role("wohaoshuai2","police","B22") #生成一個角色
print("r2",r2.ac,r2.weapon,Role.members)

r3 = Role("wohaoshuai3","police","AK47")

#r1.buy_gun("AK47") #會自動轉換成Role.buy_gun(r1,"AK47")


r1.ac = "China Brand"
r2.ac = "US Brand"

Role.ac = "riben Brand"
Role.weapon = "riben wepon"

print("r1:",r1.ac,r1.weapon,Role.members)
print("r2",r2.ac,r2.weapon,Role.members)
print("r3",r3.ac,r3.weapon,Role.members)

‘‘‘總結:
1、ac是類的屬性
2、weapon是實例屬性
3、實例訪問方法或屬性的時候其實是訪問其類的方法或屬性,無論一個類中有多少個實例對象,當他們訪問對象中的方法或屬性的時候都是調用類的方法或屬性
‘‘‘

Python 面向對象3