類--對私有變量、私有方法的理解

#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 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章