美文网首页python从0到1学习笔记
Python中面向对象的相关概念和继承

Python中面向对象的相关概念和继承

作者: 三不小青年 | 来源:发表于2018-08-16 17:36 被阅读24次

    父类

    class Human():

    sum =0

        def __init__(self, name, age, character="开朗"):# 父类构造函数

            self.name = name

    self.age = age

    self.__character = character# 私有化,子类将不能继承

            self.tell_sum()# 调用类内方法

        def __character(self):# 私有化函数,实例化对象和子类均不能访问

            print(self.__character)

    def tell_name(self):#公共函数

            print(self.name)

    @classmethod  # 装饰器,变成类方法

        def tell_sum(cls):

    cls.sum +=1

            print("我是第"+str(cls.sum)+'个人')

    @staticmethod  # 装饰器,变成静态方法

        def tell_species(sex='女'):

    print("我是个"+sex+"人")

    子类

    from mine.parentimport Human

    class Student(Human):

    sum =0

        def __init__(self, school, name, age):

    self.school = school

    super(Student, self).__init__(name, age)# 重载父类构造方法

        def print_info(self):

    print('我叫'+self.name +',' +'今年'+str(self.age)+','+'来自'+self.school)

    student1 = Student('华侨大学', 'Byron', 18)# 实例化对象

    print(student1.__dict__)# 查看对象有的属性

    student1.tell_name()# 调用父类的共有函数

    student1.print_info()# 调用类的方法

    student1.tell_species('男')# 调用类的静态方法

    打印结果

    相关文章

      网友评论

        本文标题:Python中面向对象的相关概念和继承

        本文链接:https://www.haomeiwen.com/subject/kqmobftx.html