2019年8月7日 封装 7夕快乐

 

约定1:单下划线为内部的,私有的。

约定2:双下划线为内部的

真正封装是明确区分内外,只能给内部调用,外部无法直接调用,内部逻辑外部无法知晓,并且给外部提供个借口使用

'''class H2o:
    def __init__(self,name,temperature):
        self.name=name
        self.temperature=temperature
    def turn_ice(self):
        if self.temperature<0:
            print('%s温度太低结冰了'%self.name)
        elif self.temperature > 0 and self.temperature < 100:
            print('%s液化成冰'%self.name)
        else:
            print('%s温度太高变成了水蒸气'%self.name)

class Water(H2o):
    pass

class Ice(H2o):
    pass
class Steam(H2o):
    pass

w1=Water('water',50)
i1=Ice('ice',-5)
s1=Steam('steam',150)

w1.turn_ice()
i1.turn_ice()
s1.turn_ice()'''
class People:
    _star='earth' #前面加单下划线,表达只能内部使用(People类内部)
    __sun='sun'  #双下划线
    def __init__(self,name,age,id):
        self.name=name
        self.age=age
        self.id=id

    def get_star(self):#预留接口给外部调用
        print(self._star)

p1=People('sxj',18,'111222')

print(p1._star)#还是能访问的,只不过是一种约定,单下划线不应该在外部调用
# print(p1.__sun)
print(p1._People__sun) #双下划线开头,Python会自动进行重命名

》》

earth
sun

猜你喜欢

转载自www.cnblogs.com/python1988/p/11317650.html