• python学习之面向对象(下)


    该篇主要是针对面向对象的细讲,包括类的多重继承,方法的重写,析构函数,回收机制进行讲解

    #该类主要是讲述python面象对象的一些特征,包括继承,方法的重写,多态,垃圾回收

    class person(object):
        name = ''
        age = ''

        def __init__(self,name,age, **kwargs):
            self.name = name
            self.age = age
            return super().__init__(**kwargs)
        
        def dosomething(self):
            print("my name is {0:} and age is {1}".format(self.name,self.age))

    #__del__方法为析构函数
        def __del__(self):
          class_name = self.__class__.__name__
          print(class_name, "destroyed")



    class Student(person):

        bookName = ""

        def __init__(self, book, **kwargs):
            self.bookName = book
            return super().__init__(**kwargs)

        def dosomething(self):
            print("my name is {0:} and age is {1} and learning {2}".format(self.name,self.age,self.bookName))


    class company:

        companyName = ""

        def __init__(self,company, **kwargs):
            self.companyName = company
            return super().__init__(**kwargs)

        def work(self):
            print("I work in {0}".format(self.companyName))


    class employee(Student,company):

        #def __init__(self, **kwargs):
        #    return super().__init__(**kwargs)
        pass;


    if __name__ == "__main__":

        per = person(name='Li li',age=25)
        per.dosomething()
        
        student = Student(name="ddd",age=12,book="fdfsd")
        student.dosomething()

        jack = employee(name="airvens",age=12,book="computer",company="facebook")
        jack.dosomething()
        jack.work()

        #del student回使person调用回收方法
        del per;
        del student;
        del jack;

    运行结果:

    说明:

    在python2.x版本中,对于__init__函数中初始化成员时有所不同

    3.x 版本中的写法: super().__init__(name, age)

    2.x 版本中的写法
    super(class,self).__init__(name,age)
  • 相关阅读:
    POJ 3348 Cows (凸包面积)
    P4126 [AHOI2009]最小割
    P1903 [国家集训队]数颜色
    P3749 [六省联考2017]寿司餐厅
    CF666E Forensic Examination
    P2336 [SCOI2012]喵星球上的点名
    P1117 [NOI2016]优秀的拆分
    P3747 [六省联考2017]相逢是问候
    CF1062F Upgrading Cities
    P3243 [HNOI2015]菜肴制作
  • 原文地址:https://www.cnblogs.com/airven/p/4970569.html
Copyright © 2020-2023  润新知