Python中的type函数用法
发布时间:2023-12-11 07:07:06
在Python中,type()函数用于查看给定对象的数据类型。
基本用法:
type(object):返回对象的数据类型。
例如,我们可以使用type()函数来查看不同对象的数据类型:
x = 5
print(type(x)) # <class 'int'>
y = 3.14
print(type(y)) # <class 'float'>
z = "Hello"
print(type(z)) # <class 'str'>
lst = [1, 2, 3]
print(type(lst)) # <class 'list'>
dct = {"A": 1, "B": 2}
print(type(dct)) # <class 'dict'>
在上面的例子中,type()函数分别返回了整数、浮点数、字符串、列表和字典的数据类型。
特殊情况:
1. 当对象是类(或类的实例)时,type()函数返回的是type类型。例如:
class Circle:
def __init__(self, radius):
self.radius = radius
c = Circle(5)
print(type(Circle)) # <class 'type'>
print(type(c)) # <class '__main__.Circle'>
2. 当对象是模块时,type()函数返回的是module类型。例如:
import math print(type(math)) # <class 'module'>
3. 当对象是函数时,type()函数返回的是function类型。例如:
def add(a, b):
return a + b
print(type(add)) # <class 'function'>
4. 当对象是生成器时,type()函数返回的是generator类型。例如:
gen = (x for x in range(5)) print(type(gen)) # <class 'generator'>
5. 对于用户自定义的类,type()函数返回的是type类型。例如:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 25)
print(type(Person)) # <class 'type'>
print(type(p)) # <class '__main__.Person'>
6. 对于实例化的对象,type()函数返回的是该对象所属类的类型。例如:
class Car:
def __init__(self, brand, color):
self.brand = brand
self.color = color
c = Car("BMW", "blue")
print(type(c)) # <class '__main__.Car'>
总结:
type()函数是Python中用来查看对象数据类型的函数。它可以返回各种内置数据类型(如整数、浮点数、字符串、列表、字典等)以及用户自定义的类、模块、函数和生成器的类型。通过type()函数,我们可以了解对象的数据类型,并根据需要进行相应的操作。
