在Python中,`type()`函数用于获取对象的类型信息。它是一个内置函数,可以应用于任何对象,无论是变量、常量、函数还是类。`type()`函数的基本用法是`type(object)`,其中`object`是要检查类型的对象。
用法示例:
获取整数类型的对象类型:
```python
x = 5
print(type(x)) 输出:
获取字符串类型的对象类型:
```python
s = "Hello, World!"
print(type(s)) 输出:
获取函数类型的对象类型:
```python
def hello():
print("Hello, World!")
print(type(hello)) 输出:
获取自定义类的类型:
```python
class MyClass:
pass
my_instance = MyClass()
print(type(my_instance)) 输出:
注意事项:
`type()`函数返回的是对象的类型,这是一个类型对象,不是字符串。如果需要将类型对象转换为字符串,可以使用`str()`函数。
当`type()`函数有三个参数时,它返回一个新的类型对象,用于定义类。
希望这能帮助你理解Python中`type()`函数的用途和使用方法