Python - 仅从一种类类型强制执行对象列表 [英] Python - enforce a list of objects from only one class type

查看:120
本文介绍了Python - 仅从一种类类型强制执行对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据问题,在Python2.7中,我想声明一个列表对象,它只允许管理(附加,删除等)类'X'的对象。



我能简单地做到这一点吗,我需要一个类层次结构,或者......?


$ C $ b在C中,我可能会这样做: -

as per question, in Python2.7, i want to declare a list object that only allows objects of class 'X' to be managed (appended, deleted etc.).

Can I do this simply, do I need a class hierarchy, or...??

in C, I might do:-

GenericList<float> list1 = new GenericList<float>();



任何尝试添加除float类型以外的对象,会导致错误。



类型

谢谢



我尝试了什么:



没什么 - 不知道怎么做,python似乎松散输入。


Any attempt to add an object other than type float, would result in an error.

type
Thanks

What I have tried:

Nothing - don't know how to do this , python seems loosely typed.

推荐答案

您可以使用 2。内置函数 - 实例 [ ^ ]检查对象的类型。
You can use 2. Built-in Functions — isinstance[^] to check the type of an object.


这篇关于Python - 仅从一种类类型强制执行对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆