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
coordinate
V2EX  ›  Python

super(type, obj) 和 super(type, type)的区别在哪?

  •  1
     
  •   coordinate · 2018-03-09 09:43:31 +08:00 · 2181 次点击
    这是一个创建于 2444 天前的主题,其中的信息可能已经有所发展或是发生改变。
    class Person:
        def __init__(self, name):
            self.name = name
        # Getter function
        @property
        def name(self):
            return self._name
        # Setter function
        @name.setter
        def name(self, value):       
            if not isinstance(value, str):
                raise TypeError('Expected a string')
            self._name = value
        # Deleter function
        @name.deleter
        def name(self):
            raise AttributeError("Can't delete attribute")
    
    class SubPerson(Person):
        @property
        def name(self):
            print('Getting name')
            return super().name
        @name.setter
        def name(self, value):
            print('Setting name to', value)
            super(SubPerson, SubPerson).name.__set__(self, value)
        @name.deleter
        def name(self):
            print('Deleting name')
            super(SubPerson, SubPerson).name.__delete__(self)
    
    s = SubPerson('Guido')
    print(s.name)
    

    当我将 super(SubPerson, SubPerson).name.__set__(self, value) 变成 super(SubPerson, self).name.__set__(self, value), 报了这样的错误

    AttributeError: 'SubPerson' object has no attribute '_name'

    为什么?

    第 1 条附言  ·  2018-03-09 15:37:01 +08:00
    `super([type[, object-or-type]])` 显然是可以`super(SubPerson, SubPerson)`

    If the second argument is omitted, the super object returned is unbound. If the second argument is an object, isinstance(obj, type) must be true. If the second argument is a type, issubclass(type2, type) must be true (this is useful for classmethods).

    https://docs.python.org/2/library/functions.html#super
    2 条回复    2018-03-09 15:42:41 +08:00
    ipwx
        1
    ipwx  
       2018-03-09 09:59:57 +08:00
    标准里面没有 super(SubPerson, SubPerson) 这种写法吧……即使你手头的 CPython 能工作,也不代表未来的 CPython,或者别的 Python 比如 IronPython 和 PyPy 能工作。建议规避掉这种写法。
    coordinate
        2
    coordinate  
    OP
       2018-03-09 15:42:41 +08:00
    我已经知道问题所在,结贴了:)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2902 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 21ms · UTC 14:34 · PVG 22:34 · LAX 06:34 · JFK 09:34
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.