1.私有屬性:只需要在初始化時,在屬性名前加__
class Cup: #構造函數,初始化屬性值 def __init__(self,capacity,color): #私有屬性,只需要在屬性名字前加__ self.__capacity=capacity self.color=color def retain_water(self): print("杯子顏色:"+self.color+",杯子容量:"+self.__capacity+",正在裝水.") def keep_warm(self): print("杯子顏色:"+self.color+",杯子容量:"+self.__capacity+",正在保溫.") currentCup=Cup('50ml','紫色') currentCup.retain_water()
2.私有方法:只需要在方法名前加__
class Cup: #構造函數,初始化屬性值 def __init__(self,capacity,color): #私有屬性,只需要在屬性名字前加__ self.__capacity=capacity self.color=color #私有方法,只需要在方法名前加__ def __retain_water(self): print("杯子顏色:"+self.color+",杯子容量:"+self.__capacity+",正在裝水.") def keep_warm(self): print("杯子顏色:"+self.color+",杯子容量:"+self.__capacity+",正在保溫.") currentCup=Cup('50ml','紫色') #外部調用失敗,因為__retain_water()方法是私有的 #currentCup.__retain_water() currentCup.keep_warm()
