Python继承、重写、封装的例子

Python继承、重写、封装的例子

包括三个文件 父类dog.py   子类husty.py  运行类main.py

父类dog.py :

class Dog(object):
    __slots__ = ('__name', '__kind', '__level')#私有化
    def __init__(self,name,kind,level):#构造函数,定义属性和初始方法
        self.__name=name
        self.__kind=kind
        self.__level=level#赋值
        print(f"This is a {self.__kind} dog called {self.__name} with level {self.__level}")

    def run(self):#定义类中的方法
        print(f"{self.__name} is now running!")

    def roll_over(self):
        print(f"{self.__name} is now rolling over!")

    def change_level(self):
        self.__level+=1#修改类中属性的值
        print(f"The level of {self.__name} is now {self.__level}")

子类husty.py

from Zoo.Dog import Dog#导包

class Husty(Dog):
    def __init__(self,name,kind,level):#构造函数子类继承父类的
        super(Husty,self).__init__(name,kind,level)

    def roll_over(self):#子类重写父类的方法
         print("Wow!")

    def add(self):#子类自己写的方法
        self.step=30#父类的slot对子类无作用,子类可以新建属性
        print(f"The dog`s step is {self.step}")

Main

from Zoo.Husty import Husty
from Zoo.Dog import Dog

hst=Husty("Bob","Small",2)#husty的一个实例
dg=Dog("Amy","Big",3)#dog的一个实例


hst.run()
hst.change_level()#调用两个Dog类中的函数

#子类重写了roll over方法,两次调用结果不同
hst.roll_over()
dg.roll_over()

#hst调用husty中独有的add函数
hst.add()

运行结果:

This is a Small dog called Bob with level 2
This is a Big dog called Amy with level 3
Bob is now running!
The level of Bob is now 3
Wow!
Amy is now rolling over!
The dog`s step is 30

 

你可能感兴趣的:(Python数据处理)