Python属性

标签 python properties

给定以下代码,输出似乎有点可疑。为什么“进入基地”只打印一次?为什么根本不打印“set in Base”?实际的获取/设置似乎工作正常。我错过了什么?

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

最佳答案

您需要使用 new-style classes使属性正常工作。为此,从 object 派生您的类:

class Base(object):
    ...

关于Python属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2125166/

相关文章:

python - 如何从由不同空间大小分隔的 .txt 文件中提取数据?

python - 如何有效地获取唯一值的索引列表?

.net - 使用属性引用字典中键值对的最佳方法

c# - 在 C# 中将属性作为 'out' 参数传递

javascript - Enyo 自定义属性

ios - keepCount 是否为我的 NSDate 提供了正确的信息?

python - pytz - 时区偏移量与公开信息不一致

python - 如何读取csv避免索引?

python - Pandas 删除列包含 * 的行

c# - 为对象分配属性