day 20 class inheritance

inherit

What is inherited

Inheritance refers to a new class of methods, the new class is called a word class or a derived class,

Word class inherits the parent class is called, has become a base class or superclass.

Inherited characteristics

Subclass can inherit the properties of the parent class (characteristics and skills), and can derive their own attributes (characteristics and skills)

Note: in python, a subclass can inherit more than one parent class, other languages ​​can only be a subclass inherits a parent class

Why should inherit

Inherited goal is to reduce code redundancy (decrease the code repetition)

How inheritance

1. The first thing to determine who is good and who is a subclass is the parent class.

2. When you define a class, subclass + (), write the parent class () inside, inheritance

class 父:
    x=111
    pass
class 子(父):
    pass

Inheritance early experience

#父类
class ParentClass1:
    pass

class ParentClass2:
    pass

#子类
class SubClass1(ParentClass1):
    pass

class SubClass2(ParentClass1,ParentClass2):
    pass

#查看继承的父类:__bases__,是类的属性,用来查找当前类的父类
print(SubClass1.__bases__)#(<class '__main__.ParentClass1'>,)
print(SubClass2.__bases__)#(<class '__main__.ParentClass1'>, <class '__main__.ParentClass2'>)

Looking for inheritance

How to find inheritance

To find the inheritance, we must first "first abstract, then inheritance"

What is the abstract

Extracting abstract refers to like parts, called abstract

- first abstract (abstract thought):
Obama - "Human -" Animal

McDull - "pig class -" Animal

Small - "dog -" Animal

Abstract definitions animal, called the parent class

Features:

Eyes, nose. . .

Skills:

Eating and sleeping

- re-inherited (in the program):

Obama objects - "to call mankind -" Inherit animal

McDull objects - "Calling pigs -" Inherit animal

Small - "call the dogs -" Inherit animal

Relations inherited

Object is a combination of features and skills.

It is the same class and object feature series combination of skills

Inheritance is the same characteristics as a series of skills-based conjugate

class OldboyPeople:
    school='oldboy'
    def __init__(self,name,age,sex):
        self.name=name
        self.age=age
        self.sex=sex

class OldboyStudent(OldboyPeople):
    def choose_course(self,course):
        print(f'学生{self.name}选择课程{course}')

class OldboyTeacher(OldboyPeople):
    def change_score(self):
        print(f'老师{self.name}修改分数')

stu1=OldboyStudent('nick',18,'male')
tea1=OldboyTeacher('tank',18,'male')
print(stu1.name,stu1.age,stu1.sex)
print(tea1.name,tea1.age,tea1.sex)
stu1.choose_course('python')
tea1.change_score()
'''
nick 18 male
tank 18 male
学生nick选择课程python
老师tank修改分数'''

In the context of inheritance, lookup order object properties:

1. Find an object property will first look in the name of the object in space

2. If the object does not, it will go inside to find class

3. If the current is a subclass, and no objects to find the property, will go to the parent class Find

Note: The object lookup property, if the sub-lists, regardless of the parent class has not, whichever subclass

class Foo:
    def f1(self):
        print('Foo.f1')

    def f2(self):
        print('Foo.f2')
        self.f1()

class Soo(Foo):
    def f1(self):
        print('Soo.f1')

Soo().f2()
'''
Foo.f2
Soo.f1'''

Derivation

What is the derivation

Derived refers to the subclass inherits properties of the parent class, and derive new attributes. *********

Subclassing new attribute, if the same property of the parent class, subclass places subject.

Inheritance is who is with whom the relationship, referring to the relationship between class and class, subclass the parent class affiliation

Subclass to derive new property, both properties with the parent class

method one

Directly by parent .-- init--, the --init-- use as a normal function, incoming object and inheritance of property

class OldboyPeople:
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex
class OldboyTeacher(OldboyPeople):
    # 等级, 薪资
    def __init__(self, name, age, sex, level, sal):
        OldboyPeople.__init__(self, name, age, sex)
        self.level = level
        self.sal = sal


class OldboyStudent(OldboyPeople):
    # 课程
    def __init__(self, name, age, sex, course):
        OldboyPeople.__init__(self, name, age, sex)
        self.course = course

    def choose_course(self):
        print(f'学生{self.name}选择课程{self.course}')

Second way

is a special super class, subclass to call super () will be a special object, '' points to the superclass namespace

class OldboyPeople:
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex
class OldboyTeacher(OldboyPeople):
    # 等级, 薪资
    def __init__(self, name, age, sex, level, sal):
        super().__init__(name, age, sex)
        self.level = level
        self.sal = sal


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

    def choose_course(self):
        print(f'学生{self.name}选择课程{self.course}')

Note: Do not mix the two methods

The new class of Classic

In python2, the new category will have sub-categories of classic,

In python3, all classes are new class

The new categories:

Inherited object classes are the new class

python3, the subclass does not inherit custom class will inherit the default object

Classic:

In python2, the classes are those who are not classical object of class inheritance

mro(): 属于object--> type的函数, 用来查看当前类的继承顺序, 在多继承的情况下.
class A:
    # x = 2
    pass
class B:
    # x = 3
    pass
# 多继承情况下:
class C(A, B):
    # print('C...')
    # x = 1
    pass
print(C.mro())
# [<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>]

Masonry inheritance (diamond inheritance)

Classic:

Depth-first

The new categories:

Breadth-First

# 验证
class A:
    # def test(self):
    #     print('from A')
    pass

class B(A):
    # def test(self):
    #     print('from B')
    pass

class C(A):
    def test(self):
        print('from C')
    pass

class D(B):
    # def test(self):
    #     print('from D')
    pass

class E(C):
    # def test(self):
    #     print('from E')
    pass

class F(D,E):
    # def test(self):
    #     print('from F')
    pass


# 新式类: F-D-B-E-C-A-object
f1 = F()
f1.test()

# 经典类: F-D-B-A-E-C

Json achieved by modifying inheritance

# 开源者的角度: 修改json源码
class MyJson(json.JSONEncoder):
    def default(self, o):

        # 子类派生的功能
        # 判断o是否式datetime的一个实例
        if isinstance(o, datetime):
            return o.strftime('%Y-%m-%d %X')
        elif isinstance(o, date):
            return o.strftime('%Y-%m-%d')
        else:
            # 继承父类的default方法的功能
            return super().default(self, o)


dict1 = {
    'name': 'tank',
    'today': datetime.today(),
    'today2': date.today()
}

res = json.dumps(dict1, cls=MyJson)  # cls=None,默认指向的是原json的JSONEncoder
print(res)

Guess you like

Origin www.cnblogs.com/zqfzqf/p/11649944.html