在python 3.8中强制类型边界

问题描述

我正在尝试在Python 3.8中执行类型强制,但是无法强制类型界限。让我们考虑以下示例:

class Animal(object): pass
class Cat(Animal): pass
class Dog(Animal): pass

# now want a list of only cats
list_of_cats:Cat = list()

list_of_cats.append(Cat())
list_of_cats.append(Dog()) # this should not be allowed

for animal in list_of_cats:
  print(type(animal))

---- OUTPUT -----
<class '__main__.Cat'>
<class '__main__.Dog'>

是否有一种方法可以在Python 3.8(如Scala)中使用语言功能来强制类型边界?

解决方法

这取决于您要执行的操作,但是对于像这样的简单示例,
您可以创建一个对方法进行验证的自定义类。

class Animal(object): pass

class Cat(Animal): pass

class Dog(Animal): pass

class CatList(list):
    def append(self,item):
        if isinstance(item,Cat):
            super().append(item)
        else:
            print(f'Only cats are allowed,{item} not appended')

# now want a list of only cats,use CatList class
list_of_cats: Cat = CatList()

list_of_cats.append(Cat())
list_of_cats.append(Dog())  # this should not be allowed

for animal in list_of_cats:
    print(type(animal))
Only cats are allowed,<__main__.Dog object at 0x0000016CF590A4C0> not appended
<class '__main__.Cat'>

请注意,这只是一个仅验证append方法的示例。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...