私有方法与私有字段

class Province(object):   #object表示续承属性,默认变为只读,加装饰器后是可写
memo = "中国的23个省之一"
def __init__(self,name,capital,leader,flag):
self.name = name
self.capital = capital
self.leader = leader
self.__Thailand = flag #加了__,这是私有字段,仅自己使用,也是为了安全(别人最多只能看,不能改)
def sports_meet(self):
@staticmethod
def Foo():
print ("this is Foo,in sports_meet!")
@property ##特性。有只读与可写二种,以下是只读。
def Bar(self):
return self.__Thailand
#以下是可写(装饰器加.setter,这是修改私有字段的方法):
@Bar.setter
def Bar(self,value):
self.__Thailand = value
#以下是从内部可访问到私有字段:
def show(self):
print (self.__Thailand)
#以下是私有方法:
def __sha(self):
print ("我是私有方法")
def Foo2(self):
self.__sha()
print ("(从外部通过调用内部的函数访问私有方法)")
def thailand(self):
print (self.__Thailand)
print ("从外部通过调用内部的函数访问私有字段")


japan = Province("日本","济南","小王","访问私有字段")
#print (japan.__thailand) ,直接访问不到内部的私有字段
japan.show() #间接可访问到内部的私有字段
#japan.__sha() #从外部访问不到对象内部的私有方法
japan.Foo2() ##从外部通过调用内部的函数访问私有方法
japan.thailand()
##japan.__Province.__sha() ##从外部直接访问内部的么私有方法

japan.Bar = "更改访问私有字段" ##修改私有字段的方法
japan.thailand()
原文地址:https://www.cnblogs.com/liulvzhong/p/7609764.html