python - 无法改变派生类的默认参数列表

标签 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()
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/

相关文章:

python - Django 1.11 : Dynamic Javascript to load Google Map markers

python - 如何使用 ProcessPoolExecutor 优雅地终止 loop.run_in_executor?

python - 杀死多线程SocketServer

python - 如何对列表中的每个项目应用函数

python - 为 Sqlite3 Python 更新多个值的优雅方式

python - 将 Packet.show() 表示形式放入字符串变量中

用于在 Websphere 中监控管理控制台属性的 Python 脚本

python - Jython & Bottle : SSL-enabled web server

python - 在另一个函数 python 中使用一个函数的列表

python 从字典中获取唯一值