Pytorch基础:内置类type的用法

相关阅读

Pythonicon-default.png?t=N7T8https://blog.csdn.net/weixin_45791458/category_12403403.html?spm=1001.2014.3001.5482


        在python中,一切数据类型都是对象(即类的实例),包括整数、浮点数、字符串、列表、元组、集合、字典、复数、布尔、函数、自定义类等,它们都是根据相应的类创建的。

        python内建类的定义可以在库文件/stdlib/builtins.pyi中找到,下面的例1示例性地给出了整数类型的定义。

# 例1
class int:
    @overload
    def __new__(cls, x: ConvertibleToInt = ..., /) -> Self: ...
    @overload
    def __new__(cls, x: str | bytes | bytearray, /, base: SupportsIndex) -> Self: ...
    def as_integer_ratio(self) -> tuple[int, Literal[1]]: ...
    @property
    def real(self) -> int: ...
    @property
    def imag(self) -> Literal[0]: ...
    @property
    def numerator(self) -> int: ...
    @property
    def denominator(self) -> Literal[1]: ...
    def conjugate(self) -> int: ...
    def bit_length(self) -> int: ...
    if sys.version_info >= (3, 10):
        def bit_count(self) -> int: ...

    if sys.version_info >= (3, 11):
        def to_bytes(
            self, length: SupportsIndex = 1, byteorder: Literal["little", "big"] = "big", *, signed: bool = False
        ) -> bytes: ...
        @classmethod
        def from_bytes(
            cls,
            bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer,
            byteorder: Literal["little", "big"] = "big",
            *,
            signed: bool = False,
        ) -> Self: ...
    else:
        def to_bytes(self, length: SupportsIndex, byteorder: Literal["little", "big"], *, signed: bool = False) -> bytes: ...
        @classmethod
        def from_bytes(
            cls,
            bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer,
            byteorder: Literal["little", "big"],
            *,
            signed: bool = False,
        ) -> Self: ...

    if sys.version_info >= (3, 12):
        def is_integer(self) -> Literal[True]: ...

    def __add__(self, value: int, /) -> int: ...
    def __sub__(self, value: int, /) -> int: ...
    def __mul__(self, value: int, /) -> int: ...
    def __floordiv__(self, value: int, /) -> int: ...
    def __truediv__(self, value: int, /) -> float: ...
    def __mod__(self, value: int, /) -> int: ...
    def __divmod__(self, value: int, /) -> tuple[int, int]: ...
    def __radd__(self, value: int, /) -> int: ...
    def __rsub__(self, value: int, /) -> int: ...
    def __rmul__(self, value: int, /) -> int: ...
    def __rfloordiv__(self, value: int, /) -> int: ...
    def __rtruediv__(self, value: int, /) -> float: ...
    def __rmod__(self, value: int, /) -> int: ...
    def __rdivmod__(self, value: int, /) -> tuple[int, int]: ...
    @overload
    def __pow__(self, x: Literal[0], /) -> Literal[1]: ...
    @overload
    def __pow__(self, value: Literal[0], mod: None, /) -> Literal[1]: ...
    @overload
    def __pow__(self, value: _PositiveInteger, mod: None = None, /) -> int: ...
    @overload
    def __pow__(self, value: _NegativeInteger, mod: None = None, /) -> float: ...
    # positive __value -> int; negative __value -> float
    # return type must be Any as `int | float` causes too many false-positive errors
    @overload
    def __pow__(self, value: int, mod: None = None, /) -> Any: ...
    @overload
    def __pow__(self, value: int, mod: int, /) -> int: ...
    def __rpow__(self, value: int, mod: int | None = None, /) -> Any: ...
    def __and__(self, value: int, /) -> int: ...
    def __or__(self, value: int, /) -> int: ...
    def __xor__(self, value: int, /) -> int: ...
    def __lshift__(self, value: int, /) -> int: ...
    def __rshift__(self, value: int, /) -> int: ...
    def __rand__(self, value: int, /) -> int: ...
    def __ror__(self, value: int, /) -> int: ...
    def __rxor__(self, value: int, /) -> int: ...
    def __rlshift__(self, value: int, /) -> int: ...
    def __rrshift__(self, value: int, /) -> int: ...
    def __neg__(self) -> int: ...
    def __pos__(self) -> int: ...
    def __invert__(self) -> int: ...
    def __trunc__(self) -> int: ...
    def __ceil__(self) -> int: ...
    def __floor__(self) -> int: ...
    def __round__(self, ndigits: SupportsIndex = ..., /) -> int: ...
    def __getnewargs__(self) -> tuple[int]: ...
    def __eq__(self, value: object, /) -> bool: ...
    def __ne__(self, value: object, /) -> bool: ...
    def __lt__(self, value: int, /) -> bool: ...
    def __le__(self, value: int, /) -> bool: ...
    def __gt__(self, value: int, /) -> bool: ...
    def __ge__(self, value: int, /) -> bool: ...
    def __float__(self) -> float: ...
    def __int__(self) -> int: ...
    def __abs__(self) -> int: ...
    def __hash__(self) -> int: ...
    def __bool__(self) -> bool: ...
    def __index__(self) -> int: ...

        如果一个类没有指定父类,则其默认继承object类,它是python中所有类的基类,如例2所示,注意在最后使用了issubclass函数进行了检验。

# 例2
class object:
    __doc__: str | None
    __dict__: dict[str, Any]
    __module__: str
    __annotations__: dict[str, Any]
    @property
    def __class__(self) -> type[Self]: ... # 注意这个属性
    @__class__.setter
    def __class__(self, type: type[object], /) -> None: ... 
    def __init__(self) -> None: ...
    def __new__(cls) -> Self: ...
    # N.B. `object.__setattr__` and `object.__delattr__` are heavily special-cased by type checkers.
    # Overriding them in subclasses has different semantics, even if the override has an identical signature.
    def __setattr__(self, name: str, value: Any, /) -> None: ...
    def __delattr__(self, name: str, /) -> None: ...
    def __eq__(self, value: object, /) -> bool: ...
    def __ne__(self, value: object, /) -> bool: ...
    def __str__(self) -> str: ...  # noqa: Y029
    def __repr__(self) -> str: ...  # noqa: Y029
    def __hash__(self) -> int: ...
    def __format__(self, format_spec: str, /) -> str: ...
    def __getattribute__(self, name: str, /) -> Any: ...
    def __sizeof__(self) -> int: ...
    # return type of pickle methods is rather hard to express in the current type system
    # see #6661 and https://docs.python.org/3/library/pickle.html#object.__reduce__
    def __reduce__(self) -> str | tuple[Any, ...]: ...
    def __reduce_ex__(self, protocol: SupportsIndex, /) -> str | tuple[Any, ...]: ...
    if sys.version_info >= (3, 11):
        def __getstate__(self) -> object: ...

    def __dir__(self) -> Iterable[str]: ...
    def __init_subclass__(cls) -> None: ...
    @classmethod
    def __subclasshook__(cls, subclass: type, /) -> bool: ...

print(issubclass(int, object)) # 注意使用类名int而不是int()

# 输出
True

        type是一个python内置类,例3是它的定义,如所有其他类一样,它也继承了object类。

# 例3
class type:
    # object.__base__ is None. Otherwise, it would be a type.
    @property
    def __base__(self) -> type | None: ...
    __bases__: tuple[type, ...]
    @property
    def __basicsize__(self) -> int: ...
    @property
    def __dict__(self) -> types.MappingProxyType[str, Any]: ...  # type: ignore[override]
    @property
    def __dictoffset__(self) -> int: ...
    @property
    def __flags__(self) -> int: ...
    @property
    def __itemsize__(self) -> int: ...
    __module__: str
    @property
    def __mro__(self) -> tuple[type, ...]: ...
    __name__: str
    __qualname__: str
    @property
    def __text_signature__(self) -> str | None: ...
    @property
    def __weakrefoffset__(self) -> int: ...
    @overload
    def __init__(self, o: object, /) -> None: ...
    @overload
    def __init__(self, name: str, bases: tuple[type, ...], dict: dict[str, Any], /, **kwds: Any) -> None: ...
    @overload
    def __new__(cls, o: object, /) -> type: ...
    @overload
    def __new__(
        cls: type[_typeshed.Self], name: str, bases: tuple[type, ...], namespace: dict[str, Any], /, **kwds: Any
    ) -> _typeshed.Self: ...
    def __call__(self, *args: Any, **kwds: Any) -> Any: ...
    def __subclasses__(self: _typeshed.Self) -> list[_typeshed.Self]: ...
    # Note: the documentation doesn't specify what the return type is, the standard
    # implementation seems to be returning a list.
    def mro(self) -> list[type]: ...
    def __instancecheck__(self, instance: Any, /) -> bool: ...
    def __subclasscheck__(self, subclass: type, /) -> bool: ...
    @classmethod
    def __prepare__(metacls, name: str, bases: tuple[type, ...], /, **kwds: Any) -> MutableMapping[str, object]: ...
    if sys.version_info >= (3, 10):
        def __or__(self, value: Any, /) -> types.UnionType: ...
        def __ror__(self, value: Any, /) -> types.UnionType: ...
    if sys.version_info >= (3, 12):
        __type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...]

print(issubclass(type, object)) # 注意使用类名type而不是type()

# 输出
True

        type()类可以返回一个对象(即类的实例)的类,它实际上是返回一个对象(即类的实例)的__class__属性,而__class__属性在例化一个类时会自动设置,下面的例4说明了这一点。

# 例4
a=1
b=1.0
c="1"
d=[1,2,3]
e=(1,2,3)
f={1,2,3}
g={"a":1,"b":2}
h=1+2j
i=True
def j():
    pass
class k:
    pass
kk=k()

print(type(a), a.__class__, issubclass(type(a), object))
print(type(b), b.__class__, issubclass(type(b), object))
print(type(c), c.__class__, issubclass(type(c), object))
print(type(d), d.__class__, issubclass(type(d), object))
print(type(e), e.__class__, issubclass(type(e), object))
print(type(f), f.__class__, issubclass(type(f), object))
print(type(g), g.__class__, issubclass(type(g), object))
print(type(h), h.__class__, issubclass(type(h), object))
print(type(i), i.__class__, issubclass(type(i), object))
print(type(j), j.__class__, issubclass(type(j), object))
print(type(kk), kk.__class__, issubclass(type(kk), object))

# 输出
<class 'int'> <class 'int'> True
<class 'float'> <class 'float'> True
<class 'str'> <class 'str'> True    
<class 'list'> <class 'list'> True  
<class 'tuple'> <class 'tuple'> True
<class 'set'> <class 'set'> True
<class 'dict'> <class 'dict'> True
<class 'complex'> <class 'complex'> True
<class 'bool'> <class 'bool'> True
<class 'function'> <class 'function'> True
<class '__main__.k'> <class '__main__.k'> True

        注意到在type类针对实例kk使用时,实际上返回了其类名k,因此甚至可以使用返回值再次实例化一个对象,如下例5所示。

# 例5
class k:
    pass
kk=k()
kkk=type(kk)()   # type(kk)相当于k

        如果对类名再次使用type,返回的会是type类,因为所有的类都是type这个元类的实例,如下例6所示。

# 例6
class k:
    pass
kk=k()
print(type(type(kk)))
print(isinstance(type(kk), type)) # 检测自定义类是否是type类或其父类的实例

# 输出
<class 'type'>
True

        总结来说就是,object类直接或间接是所有类的父类(可以用issubclass函数检测),而所有类又都是type类的实例(可以用isinstance函数检测)。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/595972.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

websevere服务器从零搭建到上线(四)|muduo网络库的基本原理和使用

文章目录 muduo源码编译安装muduo框架讲解muduo库编写服务器代码示例代码解析用户连接的创建和断开回调函数用户读写事件回调 使用vscode编译程序配置c_cpp_properties.json配置tasks.json配置launch.json编译 总结 muduo源码编译安装 muduo依赖Boost库&#xff0c;所以我们应…

npy文件如何追加数据?

.npy 文件是 NumPy 库用于存储数组数据的二进制格式&#xff0c;它包含一个描述数组结构的头部信息和实际的数据部分。直接追加数据到现有的 .npy 文件并不像文本文件那样直接&#xff0c;因为需要手动修改文件头部以反映新增数据后的数组尺寸&#xff0c;并且要确保数据正确地…

【哈希表】Leetcode 14. 最长公共前缀

题目讲解 14. 最长公共前缀 算法讲解 我们使用当前第一个字符串中的与后面的字符串作比较&#xff0c;如果第一个字符串中的字符没有出现在后面的字符串中&#xff0c;我们就直接返回&#xff1b;反之当容器中的所有字符串都遍历完成&#xff0c;说明所有的字符串都在该位置…

从简单逻辑到复杂计算:感知机的进化与其在现代深度学习和人工智能中的应用(上)

文章目录 引言第一章&#xff1a;感知机是什么第二章&#xff1a;简单逻辑电路第三章&#xff1a;感知机的实现3.1 简单的与门实现3.2 导入权重和偏置3.3 使用权重和偏置的实现实现与门实现与非门和或门 文章文上下两节 从简单逻辑到复杂计算&#xff1a;感知机的进化与其在现代…

微信公众号 点击显示答案 操作步骤

1、右键进入检查模式 2、ctrlf查找html元素 3、添加答案区域代码 添加答案区域代码后&#xff0c;可以直接在页面进行格式调整 <!-- 此处height控制显示区域高度 --> <section style"height: 1500px;overflow-x: hidden;overflow-y: auto;text-align: center;b…

博客网站SpringBoot+Vue项目练习

博客网站SpringBootVue简单案例 前言 学了vue后一直没用找到应用的机会&#xff0c;在Github上找到了一个看起来比较友好的项目&#xff08;其实具体代码我还没看过&#xff09;。而且这个项目作者的readme文档写的也算是比较好的了。 项目链接&#xff1a;https://github.c…

基于 Linux 自建怀旧游戏之 - 80 款 H5 精品小游戏合集

1&#xff09;简介 最近又找到了一款宝藏游戏资源分享给大家&#xff0c;包含 80 款 H5 精品小游戏&#xff0c;都是非常有趣味耐玩的游戏&#xff0c;比如 植物大战僵尸、捕鱼达人、贪吃蛇、俄罗斯方块、斗地主、坦克大战、双人五子棋、中国象棋 等等超级好玩的 H5 小游戏&…

ai续写软件哪个好?盘点3款经典好用的!

随着科技的不断发展&#xff0c;AI续写软件逐渐成为了许多内容创作者、学生、研究人员等的得力助手。这类软件能够通过机器学习和自然语言处理技术&#xff0c;为用户提供高质量的文本续写服务。但市场上众多的AI续写软件让人眼花缭乱&#xff0c;那么&#xff0c;究竟哪款AI续…

0506_IO1

思维导图&#xff1a; 练习&#xff1a; 有如下结构体 struct Student{ char name[16]; int age; double math_score; double chinese_score; double english_score; double physics_score; double chemistry_score; double bio_score; }; 申请该结构体数组&#xff0c;容量为…

AVL树浅谈

前言 大家好&#xff0c;我是jiantaoyab&#xff0c;本篇文章给大家介绍AVL树。 基本概念 AVL树&#xff08;Adelson-Velsky和Landis树&#xff09;是一种自平衡的二叉搜索树&#xff0c;得名于其发明者G. M. Adelson-Velsky和E. M. Landis。在AVL树中&#xff0c;任何节点的…

活动回放 | 如何进行全增量一体的异构数据库实时同步

以 AI领域为代表的新技术不断涌现&#xff0c;新的应用风口也逐渐清晰。为了加紧跟上技术发展的步伐&#xff0c;越来越多的企业开始着手&#xff0c;对仍以传统关系型数据库为主的应用后端进行现代化升级。 这就涉及到如何在不影响并保持现有业务系统正常运转的前提下&#xf…

专注 APT 攻击与防御—基于UDP发现内网存活主机

UDP简介&#xff1a; UDP&#xff08;User Datagram Protocol&#xff09;是一种无连接的协议&#xff0c;在第四层-传输层&#xff0c;处于IP协议的上一层。UDP有不提供数据包分组、组装和不能对数据包进行排序的缺点&#xff0c;也就是说&#xff0c;当报文发送之后&#xf…

Android 状态栏WiFi图标的显示逻辑

1. 状态栏信号图标 1.1 WIFI信号显示 WIFI信号在状态栏的显示如下图所示 当WiFi状态为关闭时&#xff0c;状态栏不会有任何显示。当WiFi状态打开时&#xff0c;会如上图所示&#xff0c;左侧表示有可用WiFi&#xff0c;右侧表示当前WiFi打开但未连接。 当WiFi状态连接时&#x…

SpringBoot整合rabbitmq使用案例

RocketMQ&#xff08;二十四&#xff09;整合SpringBoot SpringBoot整合rabbitmq使用案例 一 SpringBoot整合RocketMQ实现消息发送和接收消息生产者1&#xff09;添加依赖2&#xff09;配置文件3&#xff09;启动类4&#xff09;测试类 消息消费者1&#xff09;添加依赖2&…

python 中如何匹配字符串

python 中如何匹配字符串&#xff1f; 1. re.match 尝试从字符串的起始位置匹配一个模式&#xff0c;如果不是起始位置匹配成功的话&#xff0c;match()就返回none。 import re line"this hdr-biz 123 model server 456" patternr"123" matchObj re.matc…

iconfont_vue小程序中使用

1.前三步就是简单下载&#xff0c;详细可看这篇 vue管理系统导航中添加新的iconfont的图标-CSDN博客 2.引用有点区别&#xff1a;在App中引用 3.uni-icons写法 <uni-icons custom-prefix"iconfont" type"icon-zhengjian" size"23"></un…

情感视频素材怎么来的?8个视频素材库免费下载安装

在今天这个视觉内容对于连接和影响观众至关重要的时代&#xff0c;选择适合的视频素材变得极为关键。优质的视频素材可以极大提升您的内容质量&#xff0c;无论是在增加社交媒体的吸引力、提升商业广告的效果&#xff0c;还是丰富教育材料的表现力。以下是一些全球顶级的视频素…

基于 Llama-Index、Llama 3 和 Qdrant,构建一个 RAG 问答系统!

构建一个使用Llama-Index、Llama 3和Qdrant的高级重排-RAG系统 尽管大型语言模型&#xff08;LLMs&#xff09;有能力生成有意义且语法正确的文本&#xff0c;但它们面临的一个挑战是幻觉。 在LLMs中&#xff0c;幻觉指的是它们倾向于自信地生成错误答案&#xff0c;制造出看似…

Stateflow基础知识笔记

01--Simulink/Stateflow概述 Stateflow是集成于Simulink中的图形化设计与开发工具&#xff0c;主要 用于针对控制系统中的复杂控制逻辑进行建模与仿真&#xff0c;或者说&#xff0c; Stateflow适用于针对事件响应系统进行建模与仿真。 Stateflow必须与Simulink联合使用&#…

一个年薪30w软件测试员的职业规划,献给还在迷茫中的朋友

先抛出一个观点 &#xff0c; 那些&#xff0c;担心30岁后&#xff0c;35岁后&#xff0c;40岁后&#xff0c;无路可走的&#xff1b;基本属于能力不够、或者思维太局限 。 总之&#xff0c;瞎担心 / 不长进 。 具体&#xff0c;见下面正文 。 曾经&#xff0c;在16年&#xff…