python-8 面向对象详解:成员属性、方法、继承、私有

面向对象理解实例:成员属性、方法、继承及私有

class Person(object):
    """
    返回具有给定名称的 Person 对象
    """

    def __init__(self, name):
        self.name = name

    def get_details(self):
        """
        返回包含人名的字符串
        """
        return self.name


class Student(Person):
    """
    返回 Student 对象,采用 name, branch, year 3 个参数
    """

    def __init__(self, name, branch, year):
        Person.__init__(self, name)
        self.branch = branch
        self.year = year

    def get_details(self):
        """
        返回包含学生具体信息的字符串
        """
        return "{} studies {} and is in {} year.".format(self.name, self.branch, self.year)


class Teacher(Person):
    """
    返回 Teacher 对象,采用字符串列表作为参数
    """
    def __init__(self, name, papers):
        Person.__init__(self, name)
        self.papers = papers

    def get_details(self):
        return "{} teaches {}".format(self.name, ','.join(self.papers))


person1 = Person('Sachin')
student1 = Student('Kushal', 'CSE', 2005)
teacher1 = Teacher('Prashad', ['C', 'C++'])

print(person1.get_details())
print(student1.get_details())
print(teacher1.get_details())


# 多继承--一个类可以继承自多个类,具有父类的所有变量和方法,语法如下:
# class MyClass(Parentclass1, Parentclass2,...):
#     def __init__(self):
#         Parentclass1.__init__(self)
#         Parentclass2.__init__(self)
#         ...
#         ...

posted @ 2020-02-28 00:13  冰冷的火  阅读(73)  评论(0)    收藏  举报