如何解决在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
方法的示例。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。