如何覆盖类的__dir__方法? [英] How to override the __dir__ method for a class?
问题描述
我想为我的班级更改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屋!