温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-05-23 08:43:47 来源:网络 阅读:908 作者:坚持和学习 栏目:编程语言


```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.....")
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI