在类型声明的部分,提供的类型声明大多都是官方给定的类型,如:int,float,str,list,dict,set等等,但是某些时候当我们使用一些特殊的变量的时候,类型并不存在于官方给定的选项中。比如某些python的库创造的变量是具有自定义的类型的,这个时候该怎么操作呢?以下给出两个例子:

库当中的类型

先看案例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'lxml')
print(soup)

这是一段BeautifulSoup库的代码,如果需要将soup当作变量传递到一个函数当中,soup是什么类型的呢?可以用type()方法进行查看:

1
2
type(soup)
# <class 'bs4.BeautifulSoup'>

现在就知道了soup的类型,于是代码就能写成:

1
2
3
4
5
6
7
8
from bs4 import BeautifulSoup
import bs4 # 引入类型对象

html_doc = """<html>test</html>"""

soup = BeautifulSoup(html_doc, 'lxml')
def test(soup:bs4.BeautifulSoup):
pass

自定义的类型

如果是自定义的类型呢?什么情况下有自定义的类型?当然是将class对象当中变量传递的时候了,我们都知道实例化的对象是class或者啥的,但是class并不是对象的类型,对象的类型应该是class的名字.
所以代码如下:

1
2
3
4
5
6
7
8
9
10
class test(object):
pass

a = test()

def funcname(parm:test):
"""
docstring
"""
pass

倘若不信也可以亲自使用type()进行验证。