zoukankan      html  css  js  c++  java
  • Python_类的私有属性、私有方法

    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()
  • 相关阅读:
    冒泡排序
    选择排序
    JavaScript学习笔记---数组对象
    数字时钟
    操作字符串
    当前时间
    倒计时 定时器
    滚动文字
    查找替换文字
    JavaScript学习笔记---对象 时间对象 字符串对象
  • 原文地址:https://www.cnblogs.com/myfy/p/11685014.html
Copyright © 2011-2022 走看看