alex
alex

Reputation: 47

python class inherit affects property?

I met a weird issue. please see the code I paste below. in myclass I have a @property datef. I can set get the property; but when I make myclass inherit from mybase, I cannot set the property any more. Why?

class mybase(object):
    pass

class myclass(mybase):
    @property     
    def dataf(self): return 1

var = myclass()
print var.dataf
var.dataf = 33
print var.__dict__

Upvotes: 0

Views: 223

Answers (2)

unutbu
unutbu

Reputation: 879073

The @property decorator only works properly with new-style classes.

If you tried

class myclass:
    @property     
    def dataf(self): return 1

then myclass is an old-style class, so don't expect @property to work properly.

When instead you make myclass a subclass of mybase which in turn inherits from object, you are making myclass a new-style class. Now @property works properly.

Now you need to define a setter if you wish to be able to set the property.

class mybase(object):
    pass

class myclass(mybase):
    @property     
    def dataf(self): return 1

    @dataf.setter
    def dataf(self, value):
        self._dataf = value

var = myclass()
print var.dataf
var.dataf = 33
print var.__dict__

yields

1
{'_dataf': 33}

Upvotes: 1

Tisho
Tisho

Reputation: 8482

You need to define property getter and setter:

class mybase(object):
    pass

class myclass(mybase):
    def dataf_get(self): return getattr(self, "_data_f", None)
    def dataf_set(self, value): self._data_f = value
    dataf = property(dataf_get, dataf_set)

var = myclass()
print var.dataf
>> None
var.dataf = 33
print var.dataf
>> 33
print var.__dict__
>> {'_data_f': 33}

Upvotes: 3

Related Questions