python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python object函数

Python中object函数详解与实战

作者:alden_ygq

本文详细解析Python中所有类的基类,介绍其核心概念、基础语法和核心方法,通过自定义属性访问控制、对象缓存机制和类型安全检查等实战案例,感兴趣的可以了解一下

在 Python 中,object 是所有类的基类(即根类),所有类都直接或间接地继承自 object。理解 object 类的特性和方法对于掌握 Python 面向对象编程至关重要。以下是对 object 的详细解析与实战案例:

一、核心概念与基础语法

1.object的地位

2. 显式继承与隐式继承

# 隐式继承(Python 3 默认)
class MyClass:  # 等同于 class MyClass(object):
    pass
# 显式继承(Python 2 兼容写法)
class MyClass(object):
    pass

3. 检查继承关系

print(issubclass(int, object))  # 输出: True
print(issubclass(list, object))  # 输出: True
print(issubclass(MyClass, object))  # 输出: True

二、object类的核心方法

1.__new__()

class Singleton(object):
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance
# 使用示例
s1 = Singleton()
s2 = Singleton()
print(s1 is s2)  # 输出: True(同一实例)

2.__init__()

class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
p = Point(1, 2)
print(p.x, p.y)  # 输出: 1 2

3.__str__()和__repr__()

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        return f"Person({self.name}, {self.age})"
    def __repr__(self):
        return f"Person(name='{self.name}', age={self.age})"
p = Person("Alice", 30)
print(p)          # 调用 __str__,输出: Person(Alice, 30)
print(repr(p))    # 调用 __repr__,输出: Person(name='Alice', age=30)

4.__eq__()和__hash__()

class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __eq__(self, other):
        return isinstance(other, Point) and self.x == other.x and self.y == other.y
    def __hash__(self):
        return hash((self.x, self.y))
p1 = Point(1, 2)
p2 = Point(1, 2)
print(p1 == p2)  # 输出: True
print({p1, p2})  # 集合去重,输出: {Point(1, 2)}

5.__getattribute__()和__setattr__()

class LoggedAttributes(object):
    def __getattribute__(self, name):
        print(f"获取属性: {name}")
        return super().__getattribute__(name)
    def __setattr__(self, name, value):
        print(f"设置属性: {name} = {value}")
        super().__setattr__(name, value)
obj = LoggedAttributes()
obj.x = 10  # 输出: 设置属性: x = 10
print(obj.x)  # 输出: 获取属性: x \n 10

三、实战案例

1. 自定义属性访问控制

class ProtectedAttributes(object):
    PROTECTED = ["password", "credit_card"]
    def __setattr__(self, name, value):
        if name in self.PROTECTED:
            raise AttributeError(f"属性 {name} 是受保护的,禁止直接修改")
        super().__setattr__(name, value)
user = ProtectedAttributes()
user.name = "Alice"  # 正常设置
user.password = "secret"  # 抛出 AttributeError

2. 对象缓存机制

class CachedObjects(object):
    _cache = {}
    def __new__(cls, key):
        if key in cls._cache:
            print(f"从缓存中获取对象: {key}")
            return cls._cache[key]
        obj = super().__new__(cls)
        cls._cache[key] = obj
        print(f"创建新对象并缓存: {key}")
        return obj
a = CachedObjects("A")  # 输出: 创建新对象并缓存: A
b = CachedObjects("A")  # 输出: 从缓存中获取对象: A
print(a is b)  # 输出: True

3. 类型安全检查

class TypedAttributes(object):
    _types = {}  # 定义属性类型映射
    def __init__(self):
        for attr, attr_type in self._types.items():
            setattr(self, attr, None)  # 初始化属性
    def __setattr__(self, name, value):
        if name in self._types and value is not None:
            if not isinstance(value, self._types[name]):
                raise TypeError(f"属性 {name} 必须是 {self._types[name]} 类型")
        super().__setattr__(name, value)
class User(TypedAttributes):
    _types = {
        "name": str,
        "age": int,
        "email": str
    }
user = User()
user.name = "Alice"  # 正常设置
user.age = "30"  # 抛出 TypeError

四、深入理解与注意事项

1.object的局限性

2. 与元类(metaclass)的关系

print(type(object))  # 输出: <class 'type'>
print(isinstance(object, type))  # 输出: True
print(type(type))  # 输出: <class 'type'>

3. 性能考虑

五、与其他基类的对比

基类用途特点
object所有类的默认基类提供基础方法框架
ABC抽象基类(定义接口)不能实例化,需子类实现
NamedTuple创建不可变的简单数据类自动生成属性和方法
dataclass创建数据类自动生成 __init__ 等方法

六、总结

场景推荐实现方式
自定义对象初始化重写 __init__()
控制属性访问重写 __getattribute__/__setattr__()
对象比较和哈希重写 __eq__() 和 __hash__()
单例模式重写 __new__()
字符串表示重写 __str__() 和 __repr__()

合理利用 object 类的方法可以实现强大的功能,如属性控制、对象缓存和类型安全检查等。但需注意避免过度使用魔术方法,保持代码的简洁性和可读性。

到此这篇关于Python中object函数详解与实战的文章就介绍到这了,更多相关Python object函数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文