• 031_class_encapsulation


    #!/usr/bin/env python
    # Author:liujun

    class Role:

    n = 123; # This is a class variable stored in class(not in a object)
    name = "class name"
    n_list = []

    def __init__(self, name, role, weapon, life_value=100, money=15000):
    # This is constructor
    # The constructor is called during instantiation
    self.name = name #A member variable and it's scope is an object
    self.role = role
    self.weapon = weapon
    self.__life_value = life_value # This is a private variable
    self.money = money
    def __del__(self):
    # This is a destructor
    # The destructor is called when an object is deleted
    pass #print("%s 彻底死了。。。。" %self.name)

    def show_status(self):
    print("name:%s weapon:%s life_val:%s" %(self.name,self.weapon,self.__life_value))
    def __shot(self): # This is a private method.
    print("shooting...")

    def got_shot(self):
    self.__life_value -=50
    print("%s:ah...,I got shot..."% self.name)

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



    r1 = Role('Chenronghua', 'police', 'AK47')
    r2 = Role('liujun', 'terrorist', 'AK47')

    print(Role.n)
    print(r1.n)
    print(r2.n)

    print(Role.name)
    print(r1.name) # search name in object first,and then name in class

    r1.bullet_prove = True;
    print(r1.bullet_prove) # Add a member variable just to r1 (not r2,not Role)
    #print(r2.bullet_prove)

    del r1.weapon # Delete a member variable just from r1 (not r2, not Role)

    r1.n = 256; # You are not change the value of n in class but add a member variable to r1.
    print(Role.n)

    r1.n_list.append("from r1") # you are change n_list in class
    r1.n_list = ["add"] # You are add a new list to r1(not r2, not class)
    print(r1.n_list)
    print(r2.n_list)



  • 相关阅读:
    压缩与解压
    Ubuntu下搭建yocto
    Ubuntu 1804 进入紧急模式
    How To Configure NFS Client on CentOS 8 / RHEL 8
    Install and Configure NFS Server on RHEL 8 / CentOS 8
    结构体大小的计算
    SQL语句对数据库调优常用
    用SQL语句操作数据库高级
    windows命令行操作mysql
    创建方便的csv格式文件
  • 原文地址:https://www.cnblogs.com/liujun5319/p/9637891.html
Copyright © 2020-2023  润新知