我有一个最小化的脚本:
import random
def genvalue():
return random.randint(1, 100)
class A(object):
def __init__(self, x = genvalue()):
self.x = x
class B(A):
def __init__(self):
super(B, self).__init__()
t1 = A(10)
t2 = B()
t3 = B()
print t1.x
print t2.x
print t3.x
我想要的预期结果是 t1.x 的值为 10,另外两个具有随机值,但 t2 和 t3 具有相同的值,就像 genfunc 只被调用一次。我想在每次启动实例时调用它。有没有可能在不弄乱函数签名的情况下做到这一点?
最佳答案
默认参数在可调用创建时被评估。
目前,genvalue
在您的程序中只被调用一次,当时正在构建方法 __init__
以绑定(bind) x 的默认值
到方法。
演示:
import random
def genvalue():
print('genvalue called')
return random.randint(1, 100)
class A(object):
def __init__(self, x=genvalue()):
self.x = x
print('creating some instances...')
A()
A()
A()
print(A.__init__.__defaults__)
输出:
genvalue called
creating some instances...
(32,)
使用
class A(object):
def __init__(self, x=None):
self.x = x if x is not None else genvalue()
关于python - 无法改变派生类的默认参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53430075/