当前位置:   article > 正文

Python基础:内置类type的用法

Python基础:内置类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. # 例1
  2. class int:
  3. @overload
  4. def __new__(cls, x: ConvertibleToInt = ..., /) -> Self: ...
  5. @overload
  6. def __new__(cls, x: str | bytes | bytearray, /, base: SupportsIndex) -> Self: ...
  7. def as_integer_ratio(self) -> tuple[int, Literal[1]]: ...
  8. @property
  9. def real(self) -> int: ...
  10. @property
  11. def imag(self) -> Literal[0]: ...
  12. @property
  13. def numerator(self) -> int: ...
  14. @property
  15. def denominator(self) -> Literal[1]: ...
  16. def conjugate(self) -> int: ...
  17. def bit_length(self) -> int: ...
  18. if sys.version_info >= (3, 10):
  19. def bit_count(self) -> int: ...
  20. if sys.version_info >= (3, 11):
  21. def to_bytes(
  22. self, length: SupportsIndex = 1, byteorder: Literal["little", "big"] = "big", *, signed: bool = False
  23. ) -> bytes: ...
  24. @classmethod
  25. def from_bytes(
  26. cls,
  27. bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer,
  28. byteorder: Literal["little", "big"] = "big",
  29. *,
  30. signed: bool = False,
  31. ) -> Self: ...
  32. else:
  33. def to_bytes(self, length: SupportsIndex, byteorder: Literal["little", "big"], *, signed: bool = False) -> bytes: ...
  34. @classmethod
  35. def from_bytes(
  36. cls,
  37. bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer,
  38. byteorder: Literal["little", "big"],
  39. *,
  40. signed: bool = False,
  41. ) -> Self: ...
  42. if sys.version_info >= (3, 12):
  43. def is_integer(self) -> Literal[True]: ...
  44. def __add__(self, value: int, /) -> int: ...
  45. def __sub__(self, value: int, /) -> int: ...
  46. def __mul__(self, value: int, /) -> int: ...
  47. def __floordiv__(self, value: int, /) -> int: ...
  48. def __truediv__(self, value: int, /) -> float: ...
  49. def __mod__(self, value: int, /) -> int: ...
  50. def __divmod__(self, value: int, /) -> tuple[int, int]: ...
  51. def __radd__(self, value: int, /) -> int: ...
  52. def __rsub__(self, value: int, /) -> int: ...
  53. def __rmul__(self, value: int, /) -> int: ...
  54. def __rfloordiv__(self, value: int, /) -> int: ...
  55. def __rtruediv__(self, value: int, /) -> float: ...
  56. def __rmod__(self, value: int, /) -> int: ...
  57. def __rdivmod__(self, value: int, /) -> tuple[int, int]: ...
  58. @overload
  59. def __pow__(self, x: Literal[0], /) -> Literal[1]: ...
  60. @overload
  61. def __pow__(self, value: Literal[0], mod: None, /) -> Literal[1]: ...
  62. @overload
  63. def __pow__(self, value: _PositiveInteger, mod: None = None, /) -> int: ...
  64. @overload
  65. def __pow__(self, value: _NegativeInteger, mod: None = None, /) -> float: ...
  66. # positive __value -> int; negative __value -> float
  67. # return type must be Any as `int | float` causes too many false-positive errors
  68. @overload
  69. def __pow__(self, value: int, mod: None = None, /) -> Any: ...
  70. @overload
  71. def __pow__(self, value: int, mod: int, /) -> int: ...
  72. def __rpow__(self, value: int, mod: int | None = None, /) -> Any: ...
  73. def __and__(self, value: int, /) -> int: ...
  74. def __or__(self, value: int, /) -> int: ...
  75. def __xor__(self, value: int, /) -> int: ...
  76. def __lshift__(self, value: int, /) -> int: ...
  77. def __rshift__(self, value: int, /) -> int: ...
  78. def __rand__(self, value: int, /) -> int: ...
  79. def __ror__(self, value: int, /) -> int: ...
  80. def __rxor__(self, value: int, /) -> int: ...
  81. def __rlshift__(self, value: int, /) -> int: ...
  82. def __rrshift__(self, value: int, /) -> int: ...
  83. def __neg__(self) -> int: ...
  84. def __pos__(self) -> int: ...
  85. def __invert__(self) -> int: ...
  86. def __trunc__(self) -> int: ...
  87. def __ceil__(self) -> int: ...
  88. def __floor__(self) -> int: ...
  89. def __round__(self, ndigits: SupportsIndex = ..., /) -> int: ...
  90. def __getnewargs__(self) -> tuple[int]: ...
  91. def __eq__(self, value: object, /) -> bool: ...
  92. def __ne__(self, value: object, /) -> bool: ...
  93. def __lt__(self, value: int, /) -> bool: ...
  94. def __le__(self, value: int, /) -> bool: ...
  95. def __gt__(self, value: int, /) -> bool: ...
  96. def __ge__(self, value: int, /) -> bool: ...
  97. def __float__(self) -> float: ...
  98. def __int__(self) -> int: ...
  99. def __abs__(self) -> int: ...
  100. def __hash__(self) -> int: ...
  101. def __bool__(self) -> bool: ...
  102. def __index__(self) -> int: ...

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

  1. # 例2
  2. class object:
  3. __doc__: str | None
  4. __dict__: dict[str, Any]
  5. __module__: str
  6. __annotations__: dict[str, Any]
  7. @property
  8. def __class__(self) -> type[Self]: ... # 注意这个属性
  9. @__class__.setter
  10. def __class__(self, type: type[object], /) -> None: ...
  11. def __init__(self) -> None: ...
  12. def __new__(cls) -> Self: ...
  13. # N.B. `object.__setattr__` and `object.__delattr__` are heavily special-cased by type checkers.
  14. # Overriding them in subclasses has different semantics, even if the override has an identical signature.
  15. def __setattr__(self, name: str, value: Any, /) -> None: ...
  16. def __delattr__(self, name: str, /) -> None: ...
  17. def __eq__(self, value: object, /) -> bool: ...
  18. def __ne__(self, value: object, /) -> bool: ...
  19. def __str__(self) -> str: ... # noqa: Y029
  20. def __repr__(self) -> str: ... # noqa: Y029
  21. def __hash__(self) -> int: ...
  22. def __format__(self, format_spec: str, /) -> str: ...
  23. def __getattribute__(self, name: str, /) -> Any: ...
  24. def __sizeof__(self) -> int: ...
  25. # return type of pickle methods is rather hard to express in the current type system
  26. # see #6661 and https://docs.python.org/3/library/pickle.html#object.__reduce__
  27. def __reduce__(self) -> str | tuple[Any, ...]: ...
  28. def __reduce_ex__(self, protocol: SupportsIndex, /) -> str | tuple[Any, ...]: ...
  29. if sys.version_info >= (3, 11):
  30. def __getstate__(self) -> object: ...
  31. def __dir__(self) -> Iterable[str]: ...
  32. def __init_subclass__(cls) -> None: ...
  33. @classmethod
  34. def __subclasshook__(cls, subclass: type, /) -> bool: ...
  35. print(issubclass(int, object)) # 注意使用类名int而不是int()
  36. # 输出
  37. True

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

  1. # 例3
  2. class type:
  3. # object.__base__ is None. Otherwise, it would be a type.
  4. @property
  5. def __base__(self) -> type | None: ...
  6. __bases__: tuple[type, ...]
  7. @property
  8. def __basicsize__(self) -> int: ...
  9. @property
  10. def __dict__(self) -> types.MappingProxyType[str, Any]: ... # type: ignore[override]
  11. @property
  12. def __dictoffset__(self) -> int: ...
  13. @property
  14. def __flags__(self) -> int: ...
  15. @property
  16. def __itemsize__(self) -> int: ...
  17. __module__: str
  18. @property
  19. def __mro__(self) -> tuple[type, ...]: ...
  20. __name__: str
  21. __qualname__: str
  22. @property
  23. def __text_signature__(self) -> str | None: ...
  24. @property
  25. def __weakrefoffset__(self) -> int: ...
  26. @overload
  27. def __init__(self, o: object, /) -> None: ...
  28. @overload
  29. def __init__(self, name: str, bases: tuple[type, ...], dict: dict[str, Any], /, **kwds: Any) -> None: ...
  30. @overload
  31. def __new__(cls, o: object, /) -> type: ...
  32. @overload
  33. def __new__(
  34. cls: type[_typeshed.Self], name: str, bases: tuple[type, ...], namespace: dict[str, Any], /, **kwds: Any
  35. ) -> _typeshed.Self: ...
  36. def __call__(self, *args: Any, **kwds: Any) -> Any: ...
  37. def __subclasses__(self: _typeshed.Self) -> list[_typeshed.Self]: ...
  38. # Note: the documentation doesn't specify what the return type is, the standard
  39. # implementation seems to be returning a list.
  40. def mro(self) -> list[type]: ...
  41. def __instancecheck__(self, instance: Any, /) -> bool: ...
  42. def __subclasscheck__(self, subclass: type, /) -> bool: ...
  43. @classmethod
  44. def __prepare__(metacls, name: str, bases: tuple[type, ...], /, **kwds: Any) -> MutableMapping[str, object]: ...
  45. if sys.version_info >= (3, 10):
  46. def __or__(self, value: Any, /) -> types.UnionType: ...
  47. def __ror__(self, value: Any, /) -> types.UnionType: ...
  48. if sys.version_info >= (3, 12):
  49. __type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...]
  50. print(issubclass(type, object)) # 注意使用类名type而不是type()
  51. # 输出
  52. True

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

  1. # 例4
  2. a=1
  3. b=1.0
  4. c="1"
  5. d=[1,2,3]
  6. e=(1,2,3)
  7. f={1,2,3}
  8. g={"a":1,"b":2}
  9. h=1+2j
  10. i=True
  11. def j():
  12. pass
  13. class k:
  14. pass
  15. kk=k()
  16. print(type(a), a.__class__, issubclass(type(a), object))
  17. print(type(b), b.__class__, issubclass(type(b), object))
  18. print(type(c), c.__class__, issubclass(type(c), object))
  19. print(type(d), d.__class__, issubclass(type(d), object))
  20. print(type(e), e.__class__, issubclass(type(e), object))
  21. print(type(f), f.__class__, issubclass(type(f), object))
  22. print(type(g), g.__class__, issubclass(type(g), object))
  23. print(type(h), h.__class__, issubclass(type(h), object))
  24. print(type(i), i.__class__, issubclass(type(i), object))
  25. print(type(j), j.__class__, issubclass(type(j), object))
  26. print(type(kk), kk.__class__, issubclass(type(kk), object))
  27. # 输出
  28. <class 'int'> <class 'int'> True
  29. <class 'float'> <class 'float'> True
  30. <class 'str'> <class 'str'> True
  31. <class 'list'> <class 'list'> True
  32. <class 'tuple'> <class 'tuple'> True
  33. <class 'set'> <class 'set'> True
  34. <class 'dict'> <class 'dict'> True
  35. <class 'complex'> <class 'complex'> True
  36. <class 'bool'> <class 'bool'> True
  37. <class 'function'> <class 'function'> True
  38. <class '__main__.k'> <class '__main__.k'> True

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

  1. # 例5
  2. class k:
  3. pass
  4. kk=k()
  5. kkk=type(kk)() # type(kk)相当于k

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

  1. # 例6
  2. class k:
  3. pass
  4. kk=k()
  5. print(type(type(kk)))
  6. print(isinstance(type(kk), type)) # 检测自定义类是否是type类或其父类的实例
  7. # 输出
  8. <class 'type'>
  9. True

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/640730
推荐阅读
相关标签
  

闽ICP备14008679号