多态
什么是多态:由不同的类实例化得到的对象,调用同一个方法,执行的逻辑不同
反映的是一种运行时候的状态
继承自统一个基类
class H2O: def __init__(self,name,temp): self.Name = name self.Temp = temp def turn(self): if self.Temp < 0: print("%s 温度太低结冰了" %(self.Name)) elif self.Temp > 100: print("%s 温度太高汽化为水蒸气" %(self.Name)) elif self.Temp > 0 and self.Temp < 100: print("%s 液体" % (self.Name)) class Water(H2O): pass class Ice(H2O): pass class Stream(H2O): pass w = Water("水",25) i = Ice("冰", -20) s = Stream("气", 230) # w.turn() # i.turn() # s.turn() def fun(obj): obj.turn() fun(w) fun(i) fun(s) ''' 水 液体 冰 温度太低结冰了 气 温度太高汽化为水蒸气 '''
封装
Python不依赖语言特性去封装数据,而是通过遵循一定的数据属性和函数属性命名的约定来达到封的效果
约定一:任何以单下划线开头的名字都应该是内部的,私有的
class People: _star = "earth" def __init__(self,name,id,sex): self.Name = name self.Id = id self.Sex = sex p1 = People("zhangsan",123456,"male") print(p1._star) # earth 可以被外部访问,但我们不应该去访问,_star约定被定义为一个私有变量 # 但是python并没有真正限定它的访问权限
约定二:双下划线开头的名字
以__开头的变量名,python会自动给你重命名为_class名__变量名
class People: __star = "earth" def __init__(self,name,id,sex): self.Name = name self.Id = id self.Sex = sex p1 = People("zhangsan",123456,"male") #print(p1._star) # 报错 print(People.__dict__) ''' {'_People__star': 'earth', '__doc__': None, '__dict__': <attribute '__dict__' of 'People' objects>, '__init__': <function People.__init__ at 0x0000026EB2BA7B70>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__module__': '__main__'} ''' print(p1._People__star) # earth
为封装到内部的方法提供一个接口给外部使用
class People: __star = "earth" def __init__(self,name,id,sex): self.Name = name self.Id = id self.Sex = sex def get_star(self): print("%s" %(self.__star)) p1 = People("zhangsan",123456,"male") p1.get_star()