首页 > 其他 > 详细

类的特性、公有私有属性和析构

时间:2018-10-02 12:59:49      阅读:166      评论:0      收藏:0      [点我收藏+]
class Role(object):
country="wuxi" #公有属性
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.__eyes = ‘good ‘#定义一个私有属性

def shot(self):
    print("shooting...")
    print(self.__eyes)

def got_shot(self):
    print("ah...,I got shot...")
    self.__eyes="heat"
    print(self.__eyes)
def ttt(self):
    return self.__eyes #让外面获取私有属性,只能看不能修改

def buy_gun(self, gun_name):
    print("%s just bought %s" % (self.name,gun_name))
    self.weapon=gun_name #修改公有属性

def __del__(self):
    print("del.....run.....")

r1 = Role(‘Alex‘, ‘police‘, ‘AK47‘) # 生成一个角色
r2 = Role(‘Jack‘, ‘terrorist‘, ‘B22‘) #生成一个角色

r2.buy_gun("核弹")
print(r2.weapon)
import time
time.sleep(5)

调用方法修改过属性后再次调用属性将是被修改后的样子。(同一个实例)

类里的方法私有化

def shot2(self): # 定义一个方法
print("It‘s my own!")
r1.shot=shot2 # 把shut2传r1.shut
r1.shot(r1)

公有属性

#country="wuxi" 在类里直接定义的属性即是公有属性
#实例里自己重新定义公有属性就不会去找父类里的公有属性,要是实例里没有定义就会去父类里找。
print(r1.country)
print(r2.country)
r1.country="suzhou"
print(r1.country)
print(r2.country)

私有属性

#self.eyes=‘good ‘ #定义一个私有属性
#print(r2.
eyes) #无法直接访问,直接查看。
#r2.got_shot() #只能内部访问
#print(r2.ttt()) #让外面获取私有属性,只能看不能修改
#print(r2._Role__eyes) #强制获取私有属性信息

类的析构方法(在实例销毁的时候自动调用)

def del(self):
print("del.....run.....")

类的特性、公有私有属性和析构

原文:http://blog.51cto.com/12992048/2288341

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!