首页 > 解决方案 > 哎呀。正确传递参数

问题描述

这有效:

class Thing():
    def __init__(self):
        a=2
        exec(f'self.foo ={a} + 2')

x = Thing()
print(x.foo)

这不起作用:

a=2

class Thing(a):
    def __init__(self, a):
        exec(f'self.foo ={a} + 2')

x = Thing(a)
print(x.foo)

问题:如何使第二个示例正常工作(应该放在2里面x)?

标签: pythonpython-3.xoop

解决方案


class Thing: #Note: Not Thing(a)
    def __init__(self, a):
        self.foo = a + 2

推荐阅读