小编Ton*_*ony的帖子

什么是__methods__,为什么调用__getattr__?

我最近尝试在我的几个类上实现"传递",以允许使用该__getattr__方法调用类的特定属性上的方法.这已经在ipython中破坏了(类型)自动完成,我很想知道为什么.第一:

class MyClass(object):
    def __init__():
        #create an instance of class ClassProperty
        self.class_property = ClassProperty()

    def __getattr__(self, item):
        #pass through calls to non-existent methods, print first
        print item
        return getattr(self.class_property,item)
Run Code Online (Sandbox Code Playgroud)

当创建这个类的一个实例,然后试图制表完成在IPython中(0.12.1),似乎几个函数被调用,包括__methods__,trait_names和_getAttributeNames.

In [1]: my_class = MyClass()
In [2]: my_class.not_in_my_class<tab>
__methods__
trait_names
_getAttributeNames
Run Code Online (Sandbox Code Playgroud)

我很想知道发生了什么.

谢谢,

PS我知道这样做是非常不透明的,而且是暂时的.不过,我很好奇.

UPDATE

基于我从下面接受的答案中学到的东西,我已经能够成功地"通过"自动完成,以便ClassProperty现在存在于自动完成实例中的方法MyClass.成功通过所需的是对该__dir__方法的更新

class MyClass(object):
    def __init__():
        #create an instance of class ClassProperty
        self.class_property = ClassProperty()

    def __getattr__(self, item):
        #pass through calls to …
Run Code Online (Sandbox Code Playgroud)

python ipython magic-methods

3
推荐指数
1
解决办法
449
查看次数

标签 统计

ipython ×1

magic-methods ×1

python ×1