Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to replace a property with a regular attribute?

The base class has this:

def _management_form(self):
    # code here
    return form
management_form = property(_management_form)

In my derived class, I'm trying to write this:

self.management_form = self.myfunc()

But of course it doesn't work. It tells me "can't set attribute" because that property has no setter. But I don't want to set it, I want to redefine what "managent_form" means. I tried putting del self.managent_form first, but that didn't work either. So how do I unproperty-ize it?

like image 842
mpen Avatar asked Feb 10 '11 21:02

mpen


2 Answers

You could assign to the class, instead of the instance:

MyClass.management_form = property(self.myfunc)

Of course, this changes the class itself for all instances (even preexisting ones). If this is OK, you can also call it exactly once, rather than in every derived-class constructor (which I'm guessing is what you're doing now).

Otherwise, you can override it in the derived class in the usual manner:

class MyOtherClass(MyClass):
    def _new_mf(self):
        # Better code
        return form
    management_form = property(new_mf)
like image 159
Marcelo Cantos Avatar answered Oct 13 '22 12:10

Marcelo Cantos


You can use something like CachedAttribute implemented via a descriptor as shown here: Replace property for perfomance gain

(Unlike a standard property such a descriptor can be overridden directly by an instance attribute - in new style classes & PY3 too.)

like image 37
kxr Avatar answered Oct 13 '22 12:10

kxr