如何覆盖类的__dir__方法? [英] How to override the __dir__ method for a class?

查看:83
本文介绍了如何覆盖类的__dir__方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的班级更改dir()输出.通常,对于所有其他对象,这是通过在其类中定义自己的__dir__方法来完成的.但是,如果我在课堂上这样做,就不会被调用.

I want to change the dir() output for my class. Normally, for all other objects, it's done by defining own __dir__ method in their class. But if I do this for my class, it's not called.

class X(object):
    def __dir__():
        raise Exception("No!")

>>>dir(X)
['__class__', '__delattr__', '__dict__',....

如何更改课程的dir()输出?

推荐答案

这是因为dir调用输入类型的__dir__(相当于:type(inp).__dir__(inp)).对于类的实例,它将调用类__dir__,但是如果在类上调用,则将调用元类的__dir__.

That's because dir calls the __dir__ of the type of the input (equivalent to: type(inp).__dir__(inp)). For instances of a class it will call the classes __dir__ but if called on a class it will call the __dir__ of the meta-class.

class X(object):
    def __dir__(self):  # missing self parameter
        raise Exception("No!")

dir(X())  # instance!
# Exception: No!

因此,如果要为类(而不是类的实例)自定义dir,则需要为X添加元类:

So if you want to customize dir for your class (not instances of your class) you need to add a metaclass for your X:

import six

class DirMeta(type):
    def __dir__(cls):
        raise Exception("No!")

@six.add_metaclass(DirMeta)
class X(object):
    pass

dir(X)
# Exception: No!

这篇关于如何覆盖类的__dir__方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆