在python中覆盖类变量 [英] Overriding class variables in python
问题描述
我试图稍微了解一下Python(2.6)如何处理类,实例等,并且在某个时候,我尝试了以下代码:
I'm trying to understand a bit how Python (2.6) deals with class, instances and so on, and at a certain point, I tried this code:
#/usr/bin/python2.6
class Base(object):
default = "default value in base"
def __init__(self):
super(Base, self).__init__()
@classmethod
def showDefaultValue(cls, defl = default):
print "defl == %s" % (defl)
class Descend(Base):
default = "default value in descend"
def __init__(self):
super(Descend, self).__init__()
if __name__ == "__main__":
Descend.showDefaultValue()
输出为:默认值(以基础为单位)"
The output is: "default value in base"
我想知道为什么Descend类不会覆盖默认"字段...有什么办法可以覆盖它?为什么不覆盖它?
I was wondering why the "default" field is not overwirtten by the Descend class... Is there any way to overwrite it? Why isn't it being overwritten?
任何提示(或链接到说明性页面将不胜感激).谢谢!
Any hint (or link to an explanatory page will be appreciated). Thank you!
推荐答案
该类变量正在被覆盖.尝试
The class variable is being overwritten. Try
@classmethod
def showDefaultValue(cls):
print "defl == %s" % (cls.default,)
您的方法行不通的原因与Python对待函数的默认参数的方式有关,而不是与类属性有关.在Python定义 showDefaultValue
的绑定时,将评估 defl
的默认值,并且该操作仅执行一次.调用方法时,使用的默认值是定义时评估的默认值.
The reason your way doesn't work has more to do with the way Python treats default arguments to functions than with class attributes. The default value for defl
is evaluated at the time Python defines the binding for showDefaultValue
and this is done exactly once. When you call your method the default value used is what was evaluated at the time of definition.
在您的情况下,将 defl
绑定到 default
变量的值,就像执行 Base
.不管您以后如何调用 showDefaultValue
(即,通过 Base
还是通过 Descend
),该值在随后的所有调用中均保持不变.> showDefaultValue
.
In your case, defl
was bound to the value of the default
variable as it was during the execution of the class body form of Base
. Regardless of how you call showDefaultValue
later on (i.e., whether via Base
or via Descend
) that value remains fixed in all subsequent invocations of showDefaultValue
.
这篇关于在python中覆盖类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!