Python object类特殊方法详解:属性访问、赋值与比较机制

Owen
Owen
发布时间:2026-10-13 | 6人浏览过
原创

本文深入解析Python中object类的常用特殊方法。详细讲解__getattribute__与__getattr__在属性访问时的调用差异,__setattr__在对象初始化与赋值中的作用及重写注意事项,以及__eq__与__hash__在对象比较和哈希计算中的联动机制。此外,还涵盖__str__、__repr__的输出控制及__class__、__dict__等内置属性的实际应用场景,帮助开发者掌握Python对象模型的核心行为。

Python object类特殊方法详解:属性访问、赋值与比较机制

本文基于Python 3.8版本进行讲解。


class object:
 """ The most base type """

 # del obj.xxx或delattr(obj,'xxx')时被调用,删除对象中的一个属性
 def __delattr__(self, *args, **kwargs): # real signature unknown
 """ Implement delattr(self, name). """
 pass

 # 对应dir(obj),返回一个列表,其中包含所有属性和方法名(包含特殊方法)
 def __dir__(self, *args, **kwargs): # real signature unknown
 """ Default dir() implementation. """
 pass

 # 判断是否相等 equal ,在obj==other时调用。如果重写了__eq__方法,则会将__hash__方法置为None
 def __eq__(self, *args, **kwargs): # real signature unknown
 """ Return self==value. """
 pass

 # format(obj)是调用,实现如何格式化obj对象为字符串
 def __format__(self, *args, **kwargs): # real signature unknown
 """ Default object formatter. """
 pass

 # getattr(obj,'xxx')、obj.xxx时都会被调用,当属性存在时,返回值,不存在时报错(除非重写__getattr__方法来处理)。
 # 另外,hasattr(obj,'xxx')时也会被调用(估计内部执行了getattr方法)
 def __getattribute__(self, *args, **kwargs): # real signature unknown
 """ Return getattr(self, name). """
 pass

 # 判断是否大于等于 greater than or equal,在obj>=other时调用
 def __ge__(self, *args, **kwargs): # real signature unknown
 """ Return self>=value. """
 pass

 # 判断是否大于 greater than,在obj>other时调用
 def __gt__(self, *args, **kwargs): # real signature unknown
 """ Return self>value. """
 pass

 # 调用hash(obj)获取对象的hash值时调用
 def __hash__(self, *args, **kwargs): # real signature unknown
 """ Return hash(self). """
 pass

 def __init_subclass__(self, *args, **kwargs): # real signature unknown
 """
 This method is called when a class is subclassed.

 The default implementation does nothing. It may be
 overridden to extend subclasses.
 """
 pass

 # object构造函数,当子类没有构造函数时,会调用object的__init__构造函数
 def __init__(self): # known special case of object.__init__
 """ Initialize self. See help(type(self)) for accurate signature. """
 pass

 # 判断是否小于等于 less than or equal,在obj<=other时调用
 def __le__(self, *args, **kwargs): # real signature unknown
 """ Return self<=value. """
 pass

 # 判断是否小于 less than,在obj<other时调用
 def __lt__(self, *args, **kwargs): # real signature unknown
 """ Return self<value. """
 pass

 # 创建一个cls类的对象,并返回
 @staticmethod # known case of __new__
 def __new__(cls, *more): # known special case of object.__new__
 """ Create and return a new object. See help(type) for accurate signature. """
 pass

 # 判断是否不等于 not equal,在obj!=other时调用
 def __ne__(self, *args, **kwargs): # real signature unknown
 """ Return self!=value. """
 pass

 def __reduce_ex__(self, *args, **kwargs): # real signature unknown
 """ Helper for pickle. """
 pass

 def __reduce__(self, *args, **kwargs): # real signature unknown
 """ Helper for pickle. """
 pass

 # 如果不重写__str__,则__repr__负责print(obj)和交互式命令行中输出obj的信息
 # 如果重写了__str__,则__repr__只负责交互式命令行中输出obj的信息
 def __repr__(self, *args, **kwargs): # real signature unknown
 """ Return repr(self). """
 pass

 # 使用setattr(obj,'xxx',value)、obj.xxx=value是被调用(注意,构造函数初始化属性也要调用)
 def __setattr__(self, *args, **kwargs): # real signature unknown
 """ Implement setattr(self, name, value). """
 pass

 # 获取对象内存大小
 def __sizeof__(self, *args, **kwargs): # real signature unknown
 """ Size of object in memory, in bytes. """
 pass

 # 设置print(obj)打印的信息,默认是对象的内存地址等信息
 def __str__(self, *args, **kwargs): # real signature unknown
 """ Return str(self). """
 pass

 @classmethod # known case
 def __subclasshook__(cls, subclass): # known special case of object.__subclasshook__
 """
 Abstract classes can override this to customize issubclass().

 This is invoked early on by abc.ABCMeta.__subclasscheck__().
 It should return True, False or NotImplemented. If it returns
 NotImplemented, the normal algorithm is used. Otherwise, it
 overrides the normal algorithm (and the outcome is cached).
 """
 pass
 # 某个对象是由什么类创建的,如果是object,则是type类<class 'type'>
 __class__ = None
 # 将对象中所有的属性放入一个字典,例如{'name':'Leo','age':32}
 __dict__ = {}
 # 类的doc信息
 __doc__ = ''
 # 类属于的模块,如果是在当前运行模块,则是__main__,如果是被导入,则是模块名(即py文件名去掉.py)
 __module__ = ''

二、常用特殊方法解释

__getattribute__与__getattr__的调用差异

1. __getattribute__方法

1)触发时机

当通过对象访问属性(如obj.属性名)或使用内置函数getattr(obj, 属性名)获取属性值时,会调用此特殊方法。例如:


class Foo(object):
 def __init__(self):
 self.name = 'Alex'

 def __getattribute__(self, item):
 print("__getattribute__ in Foo")
 return object.__getattribute__(self, item)


if __name__ == '__main__':
 f = Foo()
 print(f.name) # name属性存在 或者 getattr(f,name)
 print(f.age) # age属性不存在

无论目标属性是否存在,__getattribute__都会执行。若属性存在,返回其值;若不存在,默认返回None(注:实际Python中若未找到属性且未重写__getattr__,通常会抛出AttributeError,此处依原文逻辑描述)。

需要注意的是,使用hasattr(obj, 属性名)检查属性是否存在时,内部也会触发__getattribute__方法的调用。

2)与__getattr__的区别

在类定义中重写__getattr__后,它与__getattribute__有何不同?

__getattribute__在属性访问时始终被调用,而__getattr__仅在属性查找失败(即__getattribute__抛出AttributeError)时才被调用。默认情况下,属性不存在会抛出类似AttributeError: 'Foo' object has no attribute 'age'的错误,但通过重写__getattr__可以自定义处理逻辑:


class Foo(object):
 def __init__(self):
 self.name = 'Alex'

 def __getattribute__(self, item):
 print("__getattribute__ in Foo")
 return object.__getattribute__(self, item)

 def __getattr__(self, item):
 print("%s不存在,但我可以返回一个值" % item)
 return 54


if __name__ == '__main__':
 f = Foo()
 print(f.name) # name属性存在
 print(f.age) # age属性不存在,但__getattr__方法返回了54,所以这里打印54。

运行结果如下:


__getattribute__ in Foo
Alex
__getattribute__ in Foo
age不存在,但我可以返回一个值
54

从结果可见,f.name和f.age均触发了__getattribute__,但仅f.age因属性缺失进一步调用了__getattr__。利用这一机制,可以实现从字典中动态取值或处理异常等复杂逻辑。

__setattr__在属性赋值与初始化中的作用

2. __setattr__方法

当执行obj.name = 'alex'或使用setattr(obj, 属性名, 属性值)进行属性赋值时,会调用此方法。


class Foo(object):
 def __init__(self):
  self.name = 'Alex'

 # obj.xxx = value时调用
 def __setattr__(self, key, value):
  print('setattr')
  return object.__setattr__(self, key, value)


if __name__ == '__main__':
 f = Foo()
 f.name = 'Jone' # 打印setattr
 print(f.name)

如果重写了__setattr__且未显式调用父类的__setattr__,直接使用obj.xxx = value的方式将失效。

特别提示,在类的构造函数__init__中对属性进行初始化赋值时,同样会调用该方法:


class Foo(object):
 def __init__(self):
  self.name = 'Alex' # 这里也要调用__setattr__
  ...

因此,在重写__setattr__时,初始化阶段必须使用object类的__setattr__来确保属性正确绑定:


class Local(object):
 def __init__(self):
  # 这里不能直接使用self.DIC={},因为__setattr__被重写了
  object.__setattr__(self, 'DIC', {})

 def __setattr__(self, key, value):
  self.DIC[key] = value

 def __getattr__(self, item):
  return self.DIC.get(item, None)


if __name__ == '__main__':
 obj = Local()
 obj.name = 'Alex' # 向DIC字典中存入值
 print(obj.name) # 从DIC字典中取出值

__delattr__与__dir__的基础操作

3. __delattr__方法

该方法对应del obj.属性名或delattr(obj, 属性名)操作,用于删除对象中的特定属性。


if hasattr(f,'xxx'): # 判断f对象中是否存在属性xxx
 delattr(f, 'xxx') # 如果存在则删除。当xxx不存在时删除会报错
 # del f.xxx # 同上

4. __dir__方法

对应内置函数dir(obj),用于获取对象的所有属性名及方法名列表。


f = Foo()
print(f.__dir__()) # ['name', '__module__', '__init__', '__setattr__', '__getattribute__', '__dir__', '__dict__', '__weakref__', '__doc__', '__repr__', '__hash__', '__str__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__class__']

该方法返回一个包含所有属性和方法名的列表。

__eq__与__hash__的联动机制

5. __eq__和__hash__

__eq__用于判断obj == other时的相等性,默认继承自object类的实现。


f1 = Foo()
f2 = f1
print(f1 == f2) # True
print(f1 is f2) # True
print(hash(f1) == hash(f2)) # True

默认情况下,对于同一对象f1和f2(f1 == f2),f1 is f2以及hash(f1) == hash(f2)应同时为True(或同时为False)。

若重写__eq__方法,例如改为比较对象中的特定属性:


class Foo(object):
 def __init__(self):
  self.name = 'Alex' # 这里也要调用__
  self.ccc = object.__class__
 def __eq__(self, other):
  return self.name==other.name

即当self.name == other.name时,判定两个对象相等。


f1 = Foo()
f2 = Foo()
print(f1 == f2) # True
print(f1 is f2) # False
print(hash(f1) == hash(f2)) # 抛出异常TypeError错误

此时调用hash(obj)会抛出异常,因为重写__eq__后,Python默认将__hash__设为None,导致无法计算哈希值。

总结:

若希望类成为不可哈希(unhashable)类型,只需重写__eq__而不重写__hash__,此时__hash__将被置为None,对象不可哈希。

默认提供的__hash__方法(hash(obj))对值相同的变量(类型有限制,如List不可哈希)在相同解释器下哈希值一致,但不同解释器间可能不同。若需持久化哈希值,建议使用hashlib模块。

hash与id的区别:理论上值相同的两个对象哈希值应相同,但id可能不同(仅当为同一对象,即内存地址相同时,id才相同。id(obj)是对象的唯一标识)。

对象比较与字符串表示方法

6. __gt__、__lt__、__ge__、__le__

这些方法用于定义对象间的大小比较规则,可通过重写实现自定义比较逻辑(如仅比较特定属性值)。

7. __str__和__repr__

__str__用于定义print(obj)时的字符串输出内容。


class Foo(object):
 def __init__(self):
  self.name = 'Alex'

 def __str__(self):
  return "我是Foo"


if __name__ == '__main__':
 f1 = Foo()
 print(f1) # 打印 我是Foo

在命令行环境中:


>>> class Foo(object):
...  def __str__(self):
...    return "我是Foo"
...
>>> f1 = Foo()
>>> print(f1)
我是Foo
>>> f1
<__main__.Foo object at 0x0000023BF701C550>

可见,重写__str__后,print可输出指定内容,而直接输出对象仍显示内存地址。

__repr__用于定义Python命令行直接输出obj时的内容,以及在没有重写__str__时print(obj)的输出内容。


class Foo(object):
 def __init__(self):
  self.name = 'Alex'

 def __repr__(self):
  return "我是Foo"


if __name__ == '__main__':
 f1 = Foo()
 print(f1) # 打印 我是Foo

在命令行环境中:


>>> class Foo(object):
...  def __repr__(self):
...    return "我是Foo"
...
>>> f1 = Foo()
>>> print(f1)
我是Foo
>>> f1
我是Foo

可见,仅重写__repr__时,print和直接输出均显示指定内容。

当同时重写__str__和__repr__时:


>>> class Foo():
...  def __str__(self):
...    return "我是Foo---str"
...  def __repr__(self):
...    return "我是Foo---repr"
...
>>> f1 = Foo()
>>> print(f1)
我是Foo---str
>>> f1
我是Foo---repr

可见,__str__负责print的输出,而__repr__负责命令行直接交互时的输出。

__new__、__sizeof__及内置属性

8. __new__方法

9. __sizeof__方法

10. __class__、__dict__、__module__、__doc__属性

__class__:返回创建该对象的类。


print(f1.__class__) # <class '__main__.Foo'>

__dict__:返回包含对象所有属性的字典。


print(f1.__dict__) # {'name': 'Alex'} 只有一个属性name

__module__:返回对象所属模块名。


class Foo(object):
 def __init__(self):
  self.name = 'Alex'


if __name__ == '__main__':
 f1 = Foo()
 print(f1.__module__) # 打印__main__

若类定义在当前运行模块,则__module__打印为__main__。


import test3

f = test3.Foo()
print(f.__module__) # 打印test3

若类定义在其他模块中,则打印对应的模块名。

__doc__:返回类的文档字符串(注释)。


class Foo(object):
 """
 这是一个类,名叫Foo
 """
 def __init__(self):
  self.name = 'Alex'


if __name__ == '__main__':
 f1 = Foo()
 print(f1.__doc__) # 打印 这是一个类,名叫Foo

至此,关于Python object类特殊方法的讲解结束。更多相关内容可搜索本站往期文章或继续浏览后续内容,感谢支持!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表