costy.petrisor
costy.petrisor

Reputation: 813

why doesn't the Python property set the attribute value

Consider this following code:

class Class:
    def __init__(self):
        self._value = False
    def GetValue(self):
        return self._value
    def SetValue(self, val):
        self._value = val
    Value = property(GetValue, SetValue)

c = Class()
print c._value, c.Value
False False
c.Value = True
print c._value, c.Value
False True

Why isn't the property calling my function ? (I am running Python 2.6.5 on windows)

Upvotes: 1

Views: 577

Answers (2)

Ned Batchelder
Ned Batchelder

Reputation: 375504

If you only want to access your value as a property, it's much simpler to just use an attribute:

class Class(object):
    def __init__(self):
        self.value = False

c = Class()
c.value                # False
c.value = True
c.value                # True

This isn't Java, you can simply access attributes the easy way. If in the future you find that you need to perform more logic as part of the property access, then you can change the class to use a property.

BTW: Python style is to not use Uppercased names for functions and properties, only lowercased names.

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304137

You need to use a new style class (inherit from object) for property to work

class Class(object):
    ...

Upvotes: 8

Related Questions