Skip to main content

Python 面向对象

Python 获取对象信息

在 Python 中,当你拿到一个对象的引用时,可以通过以下方法来确定对象的类型以及查看它有哪些方法或属性。主要包括函数包括 type isinstance dir hasattr

1. 查看对象类型 type isinstance

使用内置函数 type()isinstance() 来检查对象的类型:

isinstance(obj, class):检查对象是否是指定类型的实例。例如:

obj = [1, 2, 3]
print(isinstance(obj, list))  # 输出: True
print(isinstance(obj, dict))  # 输出: False

type(obj):返回对象的类型。例如:

obj = [1, 2, 3]
print(type(obj))  # 输出: <class 'list'>

2. 查看对象的方法和属性 help dir

使用以下方法可以列出对象的属性和方法:

    • 返回列表中以双下划线 __ 开头和结尾的是 Python 的魔术方法(特殊方法)。
    • 其他的是常规方法或属性。

help(obj):提供对象的详细文档,包括类型、方法和属性的说明。

obj = [1, 2, 3]
help(obj)  # 输出列表类型的详细文档

dir(obj):返回对象的所有属性和方法的列表,包括内置的和自定义的。

obj = [1, 2, 3]
print(dir(obj))  # 输出: ['__add__', ..., 'append', 'clear', 'copy', ...]

3. 函数 hasattr getattr setattr

使用 hasattr(obj, name) 检查对象是否具有某个方法或属性:

obj = [1, 2, 3]
print(hasattr(obj, 'append'))  # 输出: True
print(hasattr(obj, 'keys'))    # 输出: False

hasattr()getattr()setattr() 动态操作属性

这三个函数能动态检查、获取、设置属性。

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

p = Person("Tom")

print(hasattr(p, "name"))       # True
print(getattr(p, "name"))       # Tom

setattr(p, "age", 18)
print(p.age)                    # 18
适合写通用代码,比如 JSON ↔ 对象 转换。

4. 动态获取对象信息 inspect

如果需要更深入的检查,可以使用 inspect 模块(适合高级用途):

import inspect

obj = [1, 2, 3]
# 获取所有方法
methods = [attr for attr in dir(obj) if inspect.ismethod(getattr(obj, attr))]
print(methods)  # 输出: ['append', 'clear', 'copy', 'count', ...]

5. vars()__dict__ 查看属性字典

vars() 会返回对象的 __dict__ 属性(存放实例变量的字典)。

class Car:
    def __init__(self, brand, price):
        self.brand = brand
        self.price = price

c = Car("Tesla", 300000)
print(vars(c))      # {'brand': 'Tesla', 'price': 300000}
print(c.__dict__)   # 同样的结果
注意:内置类型(如 list)没有 __dict__,因为它们用 __slots__ 或 C 实现。

6. 用 callable() 判断对象是否可调用

可调用对象包括函数、类、实现了 __call__ 方法的实例。

print(callable(len))       # True
print(callable("hello"))   # False

7. 用 id() 获取对象的内存地址

id() 返回对象在内存中的唯一标识(CPython 中是地址)。

x = 100
print(id(x))  # 例如 140714563326192

注意事项 & 综合应用

  • 动态类型:Python 是动态类型语言,对象的类型和方法可能在运行时改变,因此总是建议在运行时检查。
  • 自定义对象:如果对象是自定义类实例,dir()help() 会显示类中定义的属性和方法。
obj = "Hello"
print(type(obj))              # 输出: <class 'str'>
print(isinstance(obj, str))   # 输出: True
print(dir(obj)[:2])           # 输出前2个属性/方法: ['__add__', '__class__']
print(hasattr(obj, 'upper'))  # 输出: True
help(str.upper)               # 查看 upper 方法的文档