首页 > Python资料 博客日记

Python基础:内置类type的用法

2024-05-28 10:00:09Python资料围观168

这篇文章介绍了Python基础:内置类type的用法,分享给大家做个参考,收藏Python资料网收获更多编程知识

相关阅读

Pythonhttps://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函数检测)。


版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐