在Python中,`type` 是一个内置函数,用于获取对象的类型。它返回一个表示对象类型的类对象,这个类对象包含了关于特定类型的名称、基类、属性、方法和模块等信息。`type` 函数的基本用法是 `type(object)`,其中 `object` 是你想要检查类型的对象。
例如,要检查一个变量的类型,你可以使用 `type()` 函数,如下所示:
```python
num = 10
print(type(num)) 输出:
name = "John"
print(type(name)) 输出:
`type` 函数不仅可以用于检查内置类型(如 `int`, `str`, `list` 等),还可以用于自定义类型,比如类和函数。
你还可以使用 `type` 函数创建新的类对象,例如:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 30)
print(type(person)) 输出:
此外,`type` 函数还可以接受额外的参数来定义类的属性和方法:
```python
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
rect = Rectangle(3, 4)
print(type(rect)) 输出:
print(rect.area()) 输出: 12
需要注意的是,`type` 函数在Python 3.x版本中是一个内置函数,而在Python 2.x版本中,`type` 是一个关键字,用于创建类。在Python 3.x中,创建类应该使用 `class` 关键字。