Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法更改派生类的默认参数列表_Python_Python 2.7 - Fatal编程技术网

Python 无法更改派生类的默认参数列表

Python 无法更改派生类的默认参数列表,python,python-2.7,Python,Python 2.7,这是一个最小化的脚本,我有: 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() t

这是一个最小化的脚本,我有:

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
在您的程序中只被调用一次,此时方法
\uuuu init\uuuu
正在生成,以便将默认值
x
绑定到该方法

演示:

输出:

genvalue called
creating some instances...
(32,)
使用


genfunc
仅调用一次-当第一次读取类描述时。参数在那里求值-不是每次创建类时都求值

而是将默认值设置为“无”,如果没有给定值,则改为在
\uuuu init\uuu
方法中生成该值

class A(object):
    def __init__(self, x=None):
        if x is None:
            x = genvalue()

        self.x = x
class A(object):
    def __init__(self, x=None):
        self.x = x if x is not None else genvalue()
class A(object):
    def __init__(self, x=None):
        if x is None:
            x = genvalue()

        self.x = x