继承

2019-12-22  本文已影响0人  wangyu2488

2019年11月27日

# coding=utf-8

class Person:
    def __init__(self, name, age):
        self.name = name  # 名字
        self.age = age  # 年龄

    def __str__(self):
        template = 'Person [name={0}, age={1}]'
        s = template.format(self.name, self.age)
        return s

    def __eq__(self, other):
        if self.name == other.name and self.age == other.age:
            return True
        else:
            return False

    def info(self):
        template = 'Person [name={0}, age={1}]'
        s = template.format(self.name, self.age)
        return s

p = Person('小赵', 18)
print(p.info())

# class Student:
#
#     def __init__(self, name, age, school):
#         [self.name](http://self.name/) = name  # 名字
#         self.age = age  # 年龄
#         self.school = school  # 所在学校
#
#     def info(self):
#         template = 'Student [name={0}, age={1}, school={2}]'
#         s = template.format(self.name, self.age, self.school)
#         return s

class Student(Person):
    def __init__(self, name, age, school):
        super().__init__(name, age)
        self.school = school  # 所在学校

    # 重写方法
    def info(self):
        template = 'Student [name={0}, age={1}, school={2}]'
        s = template.format(self.name, self.age, self.school)
        return s

s = Student('Tom', 28, '清华大学')
print(s.info())

p1 = Person('Tony', 18)
p2 = Person('Tony', 18)
print(p1 == p2)  # True
上一篇 下一篇

猜你喜欢

热点阅读