类--对私有变量、私有方法的理解
来源:互联网 发布:淘宝怎样改店名 编辑:程序博客网 时间:2024/05/20 23:39
#encoding=utf-8class 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
阅读全文
0 0
- 类--对私有变量、私有方法的理解
- 利用java反射机制,实现对类的私有变量和私有方法的访问
- 利用java反射机制,实现对类的私有变量和私有方法的访问
- 利用java反射机制,实现对类的私有变量和私有方法的访问
- OC基础—类的私有方法和私有变量
- iOS访问类的私有成员变量及私有方法
- iOS访问类的私有成员变量及私有方法
- js的私有变量和私有方法
- 私有成员变量的理解
- 类的私有变量
- 类的私有变量
- 私有变量和私有方法
- 访问私有变量,私有方法
- 私有变量和私有方法
- Python 私有变量、私有方法、类变量与实例变量
- 私有变量和私有方法private的用法
- C++ 私有成员变量的理解
- C++ 私有成员变量的理解
- 【Linux学习】之 Shell初识
- PHP反射机制原理与用法详解
- SSM环境下,获取指定数据库连接执行sql文件
- 【转】html 页面内锚点定位及跳转方法总结
- 虽然微不足道但是很有用的JAVA基础—线程一
- 类--对私有变量、私有方法的理解
- jboot
- java_se StringBuffer
- 计算机视觉三大顶级国际会议和国外知名期刊投稿
- os模块
- 【Java笔记】Week05 --- 常用类
- java7.5
- PHP操作MongoDB时的整数问题及对策说明
- kylin从入门到实战:实际案例