V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
fanhaipeng0403
V2EX  ›  Python

Python 的 __get__描述符

  •  
  •   fanhaipeng0403 · 2018-11-24 17:37:06 +08:00 · 1396 次点击
    这是一个创建于 1972 天前的主题,其中的信息可能已经有所发展或是发生改变。
    
    
    """"
    
    https://www.jb51.net/article/86749.htm
    https://python3-cookbook.readthedocs.io/zh_CN/latest/c08/p09_create_new_kind_of_class_or_instance_attribute.html
    
    
    """
    class C(object):
        """
       存在了__get__的方法的类称之为描述符类
    
        descriptor 的实例自己访问自己是不会触发__get__,而会触发__call__,只有 descriptor 作为其它类的属性的时候才会触发 __get___
        """
        a = 'abc'
    
        def __get__(self, instance, owner):
            print("__get__() is called", instance, owner)
            return self
    
    
    
    class C2(object):
        # 为了使用一个描述器,需将这个描述器的实例作为类属性放到一个类的定义中.
        d = C()  # descriptor 的实例自己访问自己是不会触发__get__,而会触发__call__,只有 descriptor 作为其它类的属性的时候才会触发 __get___
    
    
    if __name__ == '__main__':
        # 不触发
        c = C()
        print(c.a)
    
        # 触发
        c2 = C2()
        print(c2.d.a)
    
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5246 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 08:42 · PVG 16:42 · LAX 01:42 · JFK 04:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.