7. Composite type annotations

Table of contents

1 union type

2 cross type

2.1 Basic use

2.2 Differences from inheritance


1 union type

union type is OR relation

The joint type means that this variable can be of multiple types, for example a can be a number or a string

After using the joint type, changing to the specified type will not report an error

2 cross type

2.1 Basic use

The cross type is the relationship of and

The relationship between and cannot be a basic type, because an ordinary variable cannot be both a number and a string

2.2 Differences from inheritance

First of all, there is a logical difference. Inheritance is a father-son relationship, and the cross type is a brother relationship.

Let's look at the code level again. If you use cross types, sometimes it will automatically give you compatibility (not all cases, such as return values). For example, I defined fly() in both Bird and Person below. fly() has the same parameter a, one a defines a number, and the other a defines a character

At this time you define BP, the fly() of BP can be either a number or a character

When using inheritance, an error is reported directly, because the subclass cannot conflict with the parent class

Guess you like

Origin blog.csdn.net/potato123232/article/details/132044522