派生クラス

ディレクトリ

派生

  • 派生:このプロセスサブクラス新しく定義された属性は、フォークと呼ばれ、サブクラスが派生属性を使用するときに覚えておく必要があり、常に自分自身の対象となります

90-派生クラス - 遺伝.JPG

導出方法

  • 特定のクラスの名前アクセス機能によって:方法は、継承とは何の関係もありません
class OldboyPeople:
    """由于学生和老师都是人,因此人都有姓名、年龄、性别"""
    school = 'oldboy'

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


class OldboyStudent(OldboyPeople):
    """由于学生类没有独自的__init__()方法,因此不需要声明继承父类的__init__()方法,会自动继承"""

    def choose_course(self):
        print('%s is choosing course' % self.name)


class OldboyTeacher(OldboyPeople):
    """由于老师类有独自的__init__()方法,因此需要声明继承父类的__init__()"""

    def __init__(self, name, age, gender, level):
        OldboyPeople.__init__(self, name, age, gender)
        self.level = level  # 派生

    def score(self, stu_obj, num):
        print('%s is scoring' % self.name)
        stu_obj.score = num


stu1 = OldboyStudent('tank', 18, 'male')
tea1 = OldboyTeacher('nick', 18, 'male', 10)
print(stu1.__dict__)
{'name': 'tank', 'age': 18, 'gender': 'male'}
print(tea1.__dict__)
{'name': 'nick', 'age': 18, 'gender': 'male', 'level': 10}

派生方法2

  • 継承されたプロパティの関係から、厳密な検索

  • スーパー()あなたは親クラスにアクセスするために、特別な(継承関係に応じて)に設計されたオブジェクトプロパティを取得します

  • スーパー().__のinit __(自己値渡しではありません)

  • スーパーの完全な使用は、(独自のクラス、自己の名前)、あなたはpython2で完全に記述する必要がある、とのpython3はスーパーと略記することができますスーパーです()

class OldboyPeople:
    school = 'oldboy'

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


class OldboyStudent(OldboyPeople):
    def __init__(self, name, age, sex, stu_id):
        # OldboyPeople.__init__(self,name,age,sex)
        # super(OldboyStudent, self).__init__(name, age, sex)
        super().__init__(name, age, sex)
        self.stu_id = stu_id

    def choose_course(self):
        print('%s is choosing course' % self.name)


stu1 = OldboyStudent('tank', 19, 'male', 1)
print(stu1.__dict__)
{'name': 'tank', 'age': 19, 'sex': 'male', 'stu_id': 1}

おすすめ

転載: www.cnblogs.com/nickchen121/p/10987834.html