首页 > 解决方案 > 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

标签: python

解决方案


由于覆盖__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


推荐阅读