Mizipzor
Mizipzor

Reputation: 52311

Python property

The output seems a bit fishy given the following code. Why is "get in Base" only printed once? And why is not "set in Base" printed at all? The actual getting/setting seems to work fine though. What am I missing?

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

Output:

get in Base
BaseStr
Foo

Upvotes: 8

Views: 5216

Answers (2)

user256417
user256417

Reputation:

Whenever creating a new class, derive it from the object type.

Upvotes: 0

sth
sth

Reputation: 229563

You need to use new-style classes for properties to work correctly. To do so derive your class from object:

class Base(object):
    ...

Upvotes: 18

Related Questions