6

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?

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • Are you sure that's a good idea? It sounds like breaking the is-a relationship... –  Feb 10 '11 at 21:42
  • Well the way the property is defined, it reconstructs the object every time you use it, which is just stupid. I put a print statement in there, and it gets called like 10 times, and it's causing problems because I need to modify some of its properties, but its futile if its going to get replaced next time its used. I have no idea why they (Django developers) did it like this. Basically, I just want it to be constructed once, and then return that instance from then on. – mpen Feb 10 '11 at 21:44

2 Answers2

6

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)
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
  • 1
    I guess overriding it to just return the property is good enough... kind of odd that you can de-property it though. Everything else in Python is completely mutable. – mpen Feb 11 '11 at 00:27
1

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.)

kxr
  • 4,841
  • 1
  • 49
  • 32