You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断Python子类是否实现了父类的@property方法(非pass实现)

检查子类是否重写@property装饰的方法

要判断子类是否实际实现了父类中用@property装饰的something方法,核心在于对比子类的something属性的获取方法(fget)与父类的是否为同一函数对象,具体实现如下:

原理说明

父类A中的something是一个@property对象,子类默认会继承这个property。如果子类没有重写something,子类的something.fget指向的还是父类中那个空实现的函数;如果子类重写了,就会生成新的函数对象,其__code__属性与父类的不同。

你之前尝试hasattr()失败是因为无论子类是否重写,都会继承父类的property,所以始终返回True;直接用__code__失败则是因为没有正确获取到property对应的fget函数,而是直接访问了property对象本身。

实现代码

带检查逻辑的父类定义

class A:
    def __init__(self):
        # 获取父类something的fget函数
        parent_getter = A.something.fget
        # 获取当前子类的something的fget函数
        current_getter = type(self).something.fget
        
        # 对比两个函数的代码对象是否相同
        if current_getter.__code__ is not parent_getter.__code__:
            self.target_field = "特定初始化值"
        else:
            self.target_field = None

    @property
    def something(self):
        pass

测试用子类

# 未重写something的子类
class B(A):
    pass

# 重写了something的子类
class C(A):
    @property
    def something(self):
        return "子类实现的内容"

验证结果

b_instance = B()
print(b_instance.target_field)  # 输出: None

c_instance = C()
print(c_instance.target_field)  # 输出: 特定初始化值

补充说明

  • 用__code__的身份对比(is)判断更可靠,即使子类写了和父类逻辑完全一致的函数,只要是重新定义的,__code__就是不同的对象。
  • 如果子类仅修改了property的setter等其他属性但未重写fget,会被判定为未实现,符合“实际实现该方法”的需求。

内容的提问来源于stack exchange,提问作者ESBM74

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 07:57:16