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

Python类定义语法差异:class Person(object):与class Person:有何区别?

Python中class Person(object)与class Person:的差异

核心区别分Python版本来看:

  • Python 2 环境下

    • class Person(object)是新式类:明确继承自object基类,拥有新式类专属特性——比如支持super()调用父类方法、__slots__限制实例属性、属性描述符、__getattribute__方法等;用type()查看类类型时,返回<type 'type'>。
    • class Person:是经典类(旧式类):不继承任何基类,方法解析顺序(MRO)采用深度优先,没有新式类的上述特性;用type()查看类类型时,返回<type 'classobj'>。
  • Python 3 环境下
    两者完全等价。Python 3中所有类默认都是新式类,哪怕写class Person:,底层也会自动隐式继承object,所以在功能、方法查找顺序、特性支持上没有任何区别。

带父类object的类定义示例

class Person(object):
   
  # 构造函数
  def __init__(self, name, id):
    self.name = name
    self.id = id

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:55:17