Python:如何用常规属性替换属性? [英] Python: How to replace a property with a regular attribute?
问题描述
基类有这个:
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()
但这当然行不通.它告诉我无法设置属性",因为该属性没有设置器.但是我不想设置它,我想重新定义managent_form"的含义.我尝试将 del self.managent_form
放在第一位,但这也不起作用.那么我该如何取消它的属性化呢?
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?
推荐答案
您可以分配给类,而不是实例:
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)
这篇关于Python:如何用常规属性替换属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!