python - Calling builtin dir from overrided dir method in Python
问题描述
I'm trying to override the dir method in a Python class. Inside I want to call the builtin dir method, but my attempts at calling it seem to be calling my method, rather than the default implementation.
The correct way to override the __dir__ method in python This question seemed relevant but doesn't answer the question since it seems their issue was with extending a numpy class, not with calling the default dir implementation for the class
Relevant code
def __dir__(self):
return builtins.dir(self) + self.fields()
In other words I want everything that would normally be listed plus some other things, but the builtins.dir() call just calls this function recursively.
I'm testing this in Python 3.6
解决方案
由于覆盖__dir__
仅在类的实例中很重要,您可以这样做:
class Test:
def test(self):
print('hey')
def __dir__(self):
return dir(Test) + ['hello']
请注意,这dir(Test)
是不同的,dir(Test())
因为只有后者调用Test.__dir__
.
使用dir(super())
insideTest.__dir__
也有点工作,但它只为您提供父类的数据,因此dir(Test())
不会包含仅存在于类中的属性的名称Test
。
推荐阅读
- apache-spark - 为什么 Zeppelin-Spark 解释器没有挂载 Kubernetes 服务帐户
- python - 在 Python 中使用 tearDownClass 进行单元测试后清除目录
- excel - 无法设置 xVar = range from worksheet.cells(numRow, yVarColumn)
- mongodb - 如何使用 Spring MongoTemplate 查询不区分大小写和包含
- c++ - 在c ++中对单个排序数组中的2个未排序数组进行排序
- python - Python Dataframe根据列名添加新行
- java - 使用 fromCallable/fromSupplier 订阅时无法使用 Mono.error
- heroku - 如何格式化procfile以调用文件夹中的程序?
- java - 打印每个字符两次的字符串
- python-3.x - 如果满足某些条件,如何使用 tkinter 创建弹出消息?