类--对私有变量、私有方法的理解

#encoding=utf-8
class Animal(object):
    "hello kitty"
    count=0
    def __init__(self,name):
        self.name=name
        Animal.count+=1
        #私有变量self.__feather
        self.__feather=True

    def getName(self):
        return self.name

    def get_count(self):
        return Animal.count

    def get_feather(self):
        #调用私有方法和私有变量
        print self.__get_feather()
        return self.__feather

    def __get_feather(self):
        #私有方法,不可以被实例和类直接调用,要定义实例方法,在实例方法里面才可以被调用
        return "feather"

    def set_feather(self,value):
        #定义一个可以修改私有变量的规则
        # 必须从方法里面去操作,
        # 不可以通过实例去修改私有变量
        #但是可以通过类修改私有变量
        if value not in [True,False]:
            return 'value is not vaild !'
        else:
            self.__feather=value
            return self.__feather


    @classmethod
    #类方法,只在类本身生效(类本身和实例都可以调用类方法)
    def print_doc(cls,x):
        cls.x=x
        print cls.x
        return cls.__doc__

    @staticmethod
    #静态方法,只在类本身生效(类本身和实例都可以调用静态方法)
    def print_module(y):
        print y
        return Animal.__module__

if __name__=='__main__':
    a=Animal('ajin')
    #尝试通过类 Animal 去调用私有变量self.__feather,会报错:
    #AttributeError: type object 'Animal' has no attribute '__feather'
    print Animal.__feather
    #尝试通过实例 a 去调用私有变量 self.__feather,会报错:
    #AttributeError: 'Animal' object has no attribute '__feather'
    print a.__feather
    #尝试用实例 a 去调用私有方法__get_feather(),会报错:
    #AttributeError: 'Animal' object has no attribute '__get_feather'
    print a.__get_feather()
    #尝试用类 Animal 去调用私有方法__get_feather(),会报错:
    #AttributeError: type object 'Animal' has no attribute '__get_feather'
    print Animal.__get_feather()
    #用实例 a 去调用方法get_feather()来调用私有变量 self.__feather 和实例方法__get_feather()
    #self.__feather 和实例方法__get_feather()会被正常调用,结果为:feather,True
    print a.get_feather()
    #有没有方法可以强制用实例去调用实例变量呢?
    a._Animal__feather=False
    print a._Animal__feather#这是个漏洞:可以通过这个方法去直接修改私有变量,self.__feather变成False
    #此时,用上面方法就可以通过实例来修改或获取私有变量了;
    #通过实例调用实例方法来对私有变量做改变,这样可以定义修改私有变量的规则,防止被恶意篡改
    a.set_feather('hello kitty')
    print a.set_feather("125")
    print a.set_feather(False)

由此可见:
私有变量 和 私有方法 不可以直接被实例或者类本身来进行调用;
如果要想用 私有变量 和 私有方法 的话,可以在类里面写实例方法,在实例方法里面定义写操作来对私有变量和私有方法进行操作;
有一个方法可以通过实例强制调用/修改实例变量的方法:

Self._ClassName.__PraviteVariable 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值