【问题标题】:the output in reference of descriptor描述符参考的输出
【发布时间】:2014-08-22 01:29:05
【问题描述】:
class C(object):  
    a = 'abc'  
    def __getattribute__(self, *args, **kwargs):  
        print("__getattribute__() is called")  
        return object.__getattribute__(self, *args, **kwargs)  
    def __getattr__(self, name):  
        print("__getattr__() is called ")  
        return name + " from getattr"  
    def __get__(self, instance, owner):  
        print("__get__() is called", instance, owner)  
        return self  
    def foo(self, x):  
        print(x)  


class C2(object):  
    d = C()  

>>>c2=C2()
>>>c2.d  
__get__() is called <__main__.C2 object at 0x000000000297BE10> <class '__main__.C2'>  
<__main__.C object at 0x000000000297BBA8>  

我明白结果,c2.d触发了C类中的get方法。

def __get__(self, instance, owner):    
    print("__get__() is called", instance, owner)    
    return self    

它打印“get() 被调用”,实例,所有者并返回自我&lt;__main__.C object at 0x000000000297BBA8&gt;

>>> c2.d.a  
__get__() is called <__main__.C2 object at 0x000000000297BE10> <class '__main__.C2'>  
__getattribute__() is called    
'abc'  

为什么 c2.d.a 的结果不是:

__get__() is called <__main__.C2 object at 0x000000000297BE10> <class __main__.C2'>    
<__main__.C object at 0x000000000297BBA8>      
__getattribute__() is called      
'abc'      

为什么 C 类的 get 方法中的return self 不起作用?为什么输出中在 0x000000000297BBA8> 处没有 ma​​in.C 对象?

【问题讨论】:

    标签: python-3.x descriptor


    【解决方案1】:

    ma​​in.C 对象位于 0x000000000297BBA8>

    不是打印的一部分,是c2.d表达式的结果。

    【讨论】:

    • 为什么会在c2.d中输出,而在c2.d.a中不会输出?
    • @it_is_a_literature 您正在使用外壳。表达式的结果将被打印出来。
    • 为什么c2.d.a中没有打印出表达式的结果?
    • @it_is_a_literature 是 'abc'
    • 为什么在 c2.d.a 的 0x000000000297BBA8> 处没有 <__main__.c c2.d>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 2016-04-21
    • 2021-12-05
    • 2015-08-28
    • 2017-03-21
    相关资源
    最近更新 更多