• 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)



  • 相关阅读:
    C++逐行读取文本文件的正确做法
    <Android Framework 之路>Android5.1 Camera Framework(一)
    zeromq-4.1.2在windows下的编译
    Duilib应用修改程序图标方法
    gdal集成kml库的做法
    使用DWR实现JS调用服务端Java代码
    DirectUI界面编程(六)实现右键弹出菜单
    如何设计系统的错误码及错误信息
    TCP协议格式
    UDP协议
  • 原文地址:https://www.cnblogs.com/liujun5319/p/9637891.html
Copyright © 2020-2023  润新知