多态,封装,反射

1.多态

#多态
多态是指对象如何通过他们共同的属性和动作来操作及访问,而不需要考虑他们具体的类
运行时候,多种实现 反应运行时候状态
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)
    def aaaaaaa(self):
        pass
class Water(H2O):
    pass
class Ice(H2O):
    pass
class Steam(H2O):
    pass
w1=Water("",25)
i1=Ice("",-20)
s1=Steam("蒸汽",3000)

w1.turn_ice()
i1.turn_ice()
s1.turn_ice()

#以下作法,同上
def func(obj):
    obj.turn_ice()
func(w1)
func(i1)
func(s1)

2.封装prt1

class People:
    __star = "earth"
    __star1 = "earth123"
    __star2 = "earth456"
    __star3 = "earth789"
    def __init__(self,id,name,age,salary):
        print("---->",self.__star)
        self.id = id
        self.name = name
        self.age = age
        self.salary = salary
    def get_id(self):
        print("我是私有方法啊,我找到的ID是[%s]" %self.id)
    #访问函数
    def get_star(self):
        print(self.__star)
# print(People.__dict__)
p1 = People("123456789","alex","18",100000)
# print(p1.__star)
# print(People.__dict__)
# print(p1.__star)
print(p1._People__star) #方法1访问__star="earth"
p1.get_star() #方法2访问__star="earth"

将上述代码文件导入test模块。

from package import People #先运行package中代码,接着运行test中代码
p1 = People("123123123123","alex","18",100) #调用People类
p1.get_id() #调用get_id()函数

猜你喜欢

转载自www.cnblogs.com/yuyukun/p/10652658.html