gpt4 book ai didi

python - 修改内置函数

转载 作者:太空狗 更新时间:2023-10-30 00:39:27 24 4
gpt4 key购买 nike

让我们考虑任何用户定义的 pythonic 类。如果我调用 dir(obect_of_class),我会得到它的属性列表:

['__class__', '__delattr__', '__dict__', '__dir__', ... '__weakref__', 'bases', 
'build_full_name', 'candidates', ... 'update_name'].

您可以在此列表中看到两种类型的属性:

  • 内置属性,
  • 用户定义。

我需要覆盖 __dir__ 以便它只返回用户定义的属性。我该怎么做?

很明显,如果在覆盖的函数中我调用自身,它会给我无限递归。所以,我想做这样的事情:

def __dir__(self):
return list(filter(lambda x: not re.match('__\S*__', x), dir(self)))

但要避开无限递归。

一般来说,如果不想从头写一个内置函数,想修改已有的函数,如何修改?

最佳答案

使用super调用父级的 __dir__ 实现;避免递归:

import re


class AClass:

def __dir__(self):
return [x for x in super().__dir__() if not re.match(r'__\S+__$', x)]

def method(self):
pass

>>> dir(AClass())
['method']

关于python - 修改内置函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34615840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com