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()
希望与广大网友互动??
点此进行留言吧!
最后
以上就是等待小虾米最近收集整理的关于python私有类属性_Python_类的私有属性、私有方法的全部内容,更多相关python私有类属性_Python_类内容请搜索靠谱客的其他文章。
发表评论 取消回复