Pytorch基础:内置类type的用法

news2024/10/6 4:06:07

相关阅读

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.coloradmin.cn/o/1648092.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Telnet的三种配置和SSH配置

Telnet的三种配置 实验配置思路&#xff1a; 配置接口IP地址&#xff1a; R1——配置接口IP地址 R2——配置接口IP地址 认证模式为none的配置 R1——认证模式配置为none R2——测试Telnet连接R1设备 认证模式为passwrd的配置 R1——认证模式配置为password R2——测试Telnet连…

C语言例题35、判断一个数是否是回文数

题目要求&#xff1a;输入一个5位数&#xff0c;判断它是不是回文数。即12321是回文数 #include <stdio.h>int main() {int x;int ge, shi, qian, wan;printf("请输入一个5位数&#xff1a;");scanf("%d", &x);ge x % 10; //个sh…

嵌入式硬件中PCB走线与过孔的电流承载能力分析

简介 使用FR4敷铜板PCBA上各个器件之间的电气连接是通过其各层敷着的铜箔走线和过孔来实现的。 由于不同产品、不同模块电流大小不同,为实现各个功能,设计人员需要知道所设计的走线和过孔能否承载相应的电流,以实现产品的功能,防止过流时产品烧毁。 文中介绍设计和测试FR4敷…

图解HTTP(2、简单的 HTTP 协议)

HTTP 协议用于客户端和服务器端之间的通信 请求访问文本或图像等资源的一端称为客户端&#xff0c;而提供资源响应的一端称为服务器端。 通过请求和响应的交换达成通信 请求必定由客户端发出&#xff0c;而服务器端回复响应报文 请求报文是由请求方法、请求 URI、协议版本、…

Baidu Comate 智能编码助手:编程新伙伴,效率新飞跃

作者简介&#xff1a;一名云计算网络运维人员、每天分享网络与运维的技术与干货。 公众号&#xff1a;网络豆云计算学堂 座右铭&#xff1a;低头赶路&#xff0c;敬事如仪 个人主页&#xff1a; 网络豆的主页​​​​​ 目录 写在前面 一、Baidu Comate智能编码助手简介…

vue快速入门(五十七) 作用域插槽

注释很详细&#xff0c;直接上代码 上一篇 新增内容 作用域插槽实现表格删除数据 源码 App.vue <template><div id"app"><!-- 向子组件传值 --><MyTable :tableData"tableData"><!-- 接收子组件的传值&#xff0c;默认是对象格…

金三银四面试题(二十四):享元模式知多少?

什么是享元模式 享元模式&#xff08;Flyweight Pattern&#xff09;是一种结构型设计模式&#xff0c;旨在通过共享对象来减少内存使用&#xff0c;从而提高性能。它主要用于处理大量细粒度对象的情况&#xff0c;通过将这些对象的可共享部分&#xff08;内部状态&#xff09…

“A”分考试经验分享:云计算HCIE考试请注意这几点...

大家好&#xff0c;我是誉天云计算HCIE的王同学&#xff0c;于4月2日"A"分通过了云计算3.0 HCIE的认证考试。 首先感谢誉天教育对我的辅导&#xff0c;感谢苗苗老师和石老师对我的帮助&#xff0c;通过这次考试让我对华为云计算有了一定的了解。接下来我就与大家分享…

嵌入式C语言教程:实现气压监测系统

气压监测在气象学、航空和户外活动装备中非常重要。本教程将介绍如何在STM32微控制器上使用数字气压传感器实现实时气压监测系统。 一、开发环境准备 硬件要求 微控制器&#xff1a;STM32L476RG&#xff0c;具备低功耗特性和足够的处理能力。开发板&#xff1a;STM32L4 Disc…

“40法则”视角下的中国网络安全公司

“40法则”视角下国内网安上市公司2023年业绩表现 采用“40法则”衡量&#xff0c;首先需要考虑的是营收增长和利润水平的衡量指标&#xff0c;在上一篇文章中已经详细说明&#xff0c;在此不再赘述。 增长速度的衡量指标&#xff0c;可以选择公司的营业收入的同比增长率。 …

软考 系统架构设计师系列知识点之软件可靠性基础知识(11)

接前一篇文章&#xff1a;软考 系统架构设计师系列知识点之软件可靠性基础知识&#xff08;10&#xff09; 所属章节&#xff1a; 第9章. 软件可靠性基础知识 第2节 软件可靠性建模 9.2.3 软件可靠性模型模型分类 一个有效的软件可靠性模型应尽可能地将前文所述的因素在软件可…

deepin 社区月报 | 2024年4月,多款应用更新,还有线下相见!

deepin&#xff08;深度&#xff09;社区4月总览 2024年4月&#xff0c;有1131位小伙伴加入了deepin&#xff08;深度&#xff09;社区大家庭&#xff0c;目前共有论坛伙伴153,910位&#xff1b; 在4月&#xff0c;deepin V23 Beta3共进行了2次内测更新&#xff0c;共新增与更…

十七岁少女夸小沈阳:我瞅你长得有一种大海的感觉呢!

十七岁少女夸小沈阳&#xff1a;我瞅你长得有一种大海的感觉呢&#xff01; ——小品《超级大明星》&#xff08;上&#xff09;的台词 小沈阳&#xff1a;THANK YOU 哦了 不用拍 感谢大家 非常的感谢所有的好朋友们 把你们热情而洋溢的掌声呢 送给我们所有的演员 这…

手把手教你上手开源性能监控神器Arthas

前言 在日常的工作中&#xff0c;对于商业项目尤其是并发量较高的项目&#xff0c;系统在一些情况下会莫名其妙把CPU打满并且导致服务宕机&#xff0c;虽然90%的情况下&#xff0c;是迭代发版的代码有bug&#xff0c;但是既然有这个情况&#xff0c;线上出现事故了&#xff0c…

scrapy5

Pandas Pandas 是一个 Python 库&#xff0c;它提供灵活的数据结构&#xff0c;使我们与数据的交互变得非常容易。我们将使用它将数据保存在 CSV 文件中。 obj{}arr[]obj[“name”] soup.find(“span”,{“class”:”a-size-large product-title-word-break”}).text.lstrip()…

保研面试408复习 3——操作系统

文章目录 1、操作系统一、进程有哪几种状态&#xff0c;状态之间的转换、二、调度策略a.处理机调度分为三级&#xff1a;b.调度算法 标记文字记忆&#xff0c;加粗文字注意&#xff0c;普通文字理解。 为什么越写越少&#xff1f; 问就是在打瓦。(bushi) 1、操作系统 一、进程…

【毕业设计】基于微信小程序的校园快递平台系统设计与实现

1.项目介绍 如今社会上各行各业&#xff0c;都喜欢用自己行业的专属软件工作&#xff0c;互联网发展到这个时候&#xff0c;人们已经发现离不开了互联网。新技术的产生&#xff0c;往往能解决一些老技术的弊端问题。因为传统校园快递平台系统信息管理难度大&#xff0c;容错率…

【操作指南】银河麒麟高级服务器操作系统内核升级——基于4.19.90-17升级

1. 升级清单 升级包及依赖包清单如下。 kernel ARM架构 kernel-core-4.19.90-23.18.v2101.ky10.aarch64.rpm kernel-modules-4.19.90-23.18.v2101.ky10.aarch64.rpm kernel-4.19.90-23.18.v2101.ky10.aarch64.rpm kernel-modules-extra-4.19.90-23.18.v2101.ky10.aarch64.r…

论文阅读-THE GENERALIZATION GAP IN OFFLINE REINFORCEMENT LEARNING(ICLR 2024)

1.Motivation 本文希望比较online RL、offline RL、序列决策和BC等方法的泛化能力(对于不同的初始状态、transition functions、reward functions&#xff0c;现阶段offline RL训练的方式都是在同一个环境下的数据集进行训练)。实验发现offline的算法相较于online算法对新环境…

某制造公司屋顶分布式光伏发电案例分享--分布式光伏电力监控系统解决方案

安科瑞薛瑶瑶18701709087/17343930412 ★分布式光伏监控系统 分布式光伏监控电力系统遵循安全可靠、经济合理原则&#xff0c;满足电力系统自动化总体规划要求&#xff0c;且充分考虑光伏发电的因素&#xff0c;对分布式光伏发电、用电进行集中监控、统一调度、统一运维、满足…