代码之家  ›  专栏  ›  技术社区  ›  Mizipzor

Python属性

  •  8
  • Mizipzor  · 技术社区  · 16 年前

    考虑到下面的代码,输出似乎有点可疑。为什么“进入基地”只打印一次?为什么根本不打印“固定在底座上”?不过,实际的获取/设置似乎很好。我错过了什么?

    class Base:
        def __init__(self):
            self.s = "BaseStr"
    
        def getstr(self):
            print "get in Base"
            return self.s
        def setstr(self, s):
            print "set in Base"
            self.s = s
        str = property(getstr, setstr)
    
    b = Base()
    print b.str
    b.str = "Foo"
    print b.str
    

    get in Base
    BaseStr
    Foo
    
    2 回复  |  直到 16 年前
        1
  •  18
  •   sth    16 年前

    你需要使用 new-style classes object :

    class Base(object):
        ...
    
        2
  •  0
  •   user256417 user256417    16 年前

    无论何时创建新类,都要从 object