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

一个 Property decorator 的例子 , 运行后跟书上的不一样

  •  
  •   reloop · 2015-01-08 17:54:40 +08:00 · 2787 次点击
    这是一个创建于 3367 天前的主题,其中的信息可能已经有所发展或是发生改变。
    # person2.py
    class person:
      def __init__(self,name='', age=0):
        self._name = name
        self._age = age
    
      @property
      def age(self):
        return self._age
    
      @age.setter
      def age(self, age):
        if 0 < age <= 150:
          self._age = age
    
      def set_age(self, age):
        if 0 < age <= 150:
          self._age = age
    
      def __str__(self):
        return "person(%s , %s)" % (self._name, self._age)
    
      def __repr__(self):
        return str(self)
    

    然后

    >>> import person2 as pe
    >>> p = pe.person('Lia' , 20)
    >>> p
    person(Lia, 20)
    >>> p.age
    20
    >>> p.age = 33
    >>> p.age
    33
    >>> p
    person( Lia, 20) # 为什么这里不会改变?
    >>> p.set_age(100)
    >>>p
    person(Lia, 100)
    >>>p.age
    33 # 不是100 么?
    

    书上用的 python3 我在 fedora 上用的 python2.7
    是这个原因吗?

    6 条回复    2015-01-09 14:35:54 +08:00
    regex
        1
    regex  
       2015-01-08 18:42:44 +08:00   ❤️ 1
    python3下两个问题都不存在。。
    输出为person( Lia, 33)和100
    lcqtdwj
        2
    lcqtdwj  
       2015-01-08 19:00:50 +08:00
    class person(object)
    reloop
        3
    reloop  
    OP
       2015-01-09 08:12:47 +08:00
    @lcqtdwj 谢谢 , 测试成功
    是不是可以总结成
    只要用到 `@property` , 都要继承 Object 类?
    mengzhuo
        4
    mengzhuo  
       2015-01-09 10:43:02 +08:00   ❤️ 1
    @reloop

    这是新老class的问题╮(╯▽╰)╭
    lcqtdwj
        5
    lcqtdwj  
       2015-01-09 14:26:52 +08:00   ❤️ 1
    @reloop python2自定义类现在都要继承object,new-style对象。
    reloop
        6
    reloop  
    OP
       2015-01-09 14:35:54 +08:00
    @mengzhuo
    @lcqtdwj

    谢谢!!!!!!!!!!!!!!!!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   966 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 20:31 · PVG 04:31 · LAX 13:31 · JFK 16:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.