简体   繁体   中英

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__

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}

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM