python3-type

1、介绍

type本身是内建模块中的一个类,其主要作用是用于判断变量的数据类型。

2、类

class type(object):
    def __init__(cls, what, bases=None, dict=None):
        """
        type(object_or_name, bases, dict)
        type(object) -> the object's type
        type(name, bases, dict) -> a new type

        """
        pass
  • 一个参数,作用是判断变量的数据类型
  • 三个参数,基于此创建指定类型的变量
    • name,str类型,新创建对象的类型名
    • bases,tuple类型,name指向类的父类,如果没有的话写入object即可
    • dict,dict类型,name指向的类初始化需要的参数
    • 返回即为创建的对象类型

3、示例

(1)获取类型

print(type(type("")))  # <class 'type'>
print(type("123"))  # <class 'str'>
print(type(123))  # <class 'int'>

 

import api
import os
print(type(api))
print(type(os))
"""
<class 'module'>
<class 'module'>
"""
  • 对于文件夹对应的包、或者py文件对应的模块,其对象的类型都是module
def fun():
    pass
print(type(fun))
"""
<class 'function'>
"""
  • 函数对应的类型是function
class Stu:
    def fun(self):
        pass
print(type(Stu))
print(type(Stu()))
print(type(Stu().fun))
"""
<class 'type'>
<class '__main__.Stu'>
<class 'method'>
"""
  • 类对象的类型对应的是type
  • 类创建的对象的类型,对应的是类本身
  • 类的方法的类型,对应的是method 

(2)判断类型

if type("123") == str:  # 判断类型
    print("相同")

(3)创建对象

class stu:
    def __init__(self, name):
        self.name = name


z = type("stu", (object,), {"name": "abc"})
print(z)  # <class '__main__.stu'>
print(z.name)  # abc

 

posted @ 2023-04-17 09:55  挖洞404  阅读(45)  评论(0编辑  收藏  举报