# -*- coding: utf-8 -*-"" "created on sun nov 13 23:19:03 2016@author: toby "" "#知识点: Private Method and private field ' ' Scenario: a private method or private field ' class province that you do not want to be externally accessed, or that you do not want to expose to the outside: memo = ' one of china\ ' s 23 provinces ' #静态字段 def __init__ (Self,name,capital,leadership,flag): self. name = name #动态字段 self. capital = capital #动态字段 self. leadership = leadership #动态字段 self.__thailang = flag #定义一个私有字段 #定义一个方法 for internal access to private fields, Allow external access to this private field indirectly def show (self): Print self.__thailang #也可以通过 @property Decorator, constructs a feature to access private fields internally, allowing external access to this private field indirectly @property def thailang (self): return self.__Thailang #定义个私有方法 def __sha (self): print ' hello world! ' #定义个公有方法, implement internal access to private methods, allowing external access to this private method indirectly Def foo2 (self): self.__sha () if __name__ == "__main__": #实例化两个对象, the object names are: HB, sd japan = province (' Riben ', ' Shjiazhuang ', ' Liyang ', True) #值True传递给self. __ thailang #外部尝试访问私有字段提是无法访问的 #print Japan.__thailang #间接的访问私有字段 japan.show () #外部访问私有方法, is inaccessible #japan. __sha () #访问公有方法 to implement indirect access to private method japan. Foo2 () #访问一下刚才通过 @property Decorator construction method to see if you can access the private field, the answer is yes japan. Thailang
This article is from the "Fa&it-Q Group: 223843163" blog, please be sure to keep this source http://freshair.blog.51cto.com/8272891/1874224
Python's simple chat private methods and private fields