Python type类具体的三大分类介绍

原文地址:http://developer.51cto.com/art/201003/188766.htm

 

Python type类视角中的对象体系需要我们不断的学习,其中我们使用的时候需要注意。下面我们就看看如何才能更好的运用Python type类。下面的文章希望大家有所收获。

在单纯的Python type类的世界中,一切都是对象.这些对象可以分为三类,

metaclasses,classes,instance

其中classes又可以分为内置的type和用户自定义的class

下面我们通过一张图片来作详细的说明

 

其中C的定义的方式如下(python 中继承于某类直接写在类名后面的括号中):

class C(object): ...... 其中实线表示 is-kind-of 的关系 ,虚线表示is-instance-of的关系。

查看当前classes对象(instances对象没有__bases__属性)的基类的时候,可以用过classes_name.__bases__进行查看,其值为一个Tuple元组(Python支持多继承).

查看当前对象的类型的方法是object_name.__class__

我们可以通过一些测试来证实上面的图:

这里,Python type类中的所有类。

### Python 列表分类方法 Python 中的列表可以基于不同标准进行分类处理。主要可以通过内置函数和自定义逻辑实现多种分类方式。 #### 使用 `type()` 函数区分不同型元素 对于包含混合型的列表,`type()` 可用于识别并分离特定数据型的项目: ```python mixed_list = ['apple', 1, 'banana', 2.5, True] string_items = [item for item in mixed_list if isinstance(item, str)] numeric_items = [item for item in mixed_list if isinstance(item, (int, float))] boolean_items = [item for item in mixed_list if isinstance(item, bool)] print(f"String items: {string_items}") print(f"Numeric items: {numeric_items}") print(f"Boolean items: {boolean_items}") ``` 此代码片段展示了如何通过型检查来分割原始列表中的字符串、数值以及布尔值[^1]。 #### 基于条件表达式的过滤 除了按数据型划分外,还可以依据具体业务需求设定规则来进行筛选。例如只保留长度大于三字符的单词: ```python words = ["cat", "dog", "elephant", "bird"] long_words = [word for word in words if len(word) > 3] short_words = [word for word in words if len(word) <= 3] print(f"Longer than three letters: {long_words}") print(f"Three or fewer letters: {short_words}") ``` 这段程序说明了怎样利用简单的条件语句完成对列表内项目的进一步细分。 #### 应用集合操作去重 当面对可能存在重复项的数据集时,转换成 set 型能有效去除冗余条目后再转回 list 形式继续工作: ```python duplicates_removed = list(set([1, 2, 2, 3, 4, 4])) print(duplicates_removed) ``` 上述例子体现了借助集合特性简化含有重复成员的列表结构的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值