多态&封装
多态
‘‘‘ 多态 执行时候的一种状态 ‘‘‘ ‘‘‘ 类继承有2层意义: 1.改变 2.扩张 多态就是类的这两层意义的一个具体的实现方式 即,调用不同的类实例化得对象下的相同的方法,实现的过程不一样、 python 中的标准类型就是多态概念的一个很好的示范 ‘‘‘
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)
elif self.temperature > 100:
print(‘[%s] 温度太高变成水蒸气‘%self.name)
class Water(H2O):
pass
class Ice(H2O):
pass
class steam(H2O):
pass
w1 = Water(‘水‘,25)
i1 = Ice(‘冰‘,-20)
s1 = steam(‘蒸汽‘,333)
# w1.turn_ice()
# i1.turn_ice()
# s1.turn_ice()
def func(obj):
obj.turn_ice()
func(w1) #[水]液化成冰
func(i1) #[冰] 温度太低结冰了
func(s1) #蒸汽] 温度太高变成水蒸气
封装
class People:
_start = ‘1234‘
__start1 = ‘5678‘
def __init__(self,id,name,age,salary):
self.id = id
self.name = name
self.age = age
self.salary = salary
def get_id(self):
print(‘%s‘%self.id)
p = People(200000,‘yy‘,1,2000000)
print(p._start) #1234
print(People._start) #1234
print(p.__dict__)
print(People.__dict__) #里面包含 ‘_People__start1‘: ‘5678‘
print(People._People__start1) #5678
print(p._People__start1) #5678
原文:https://www.cnblogs.com/augustyang/p/9092617.html