Python: 打印基础 class 变量

Python: print base class variables

我正在使用库在 C++、VHDL 和 SystemVerilog 之间共享数据。它使用代码生成器来构建包含适当字段的数据结构。想想一个 c 类型的数据结构。我想生成 python 包含数据结构的代码和 read/write 函数来设置数据结构的内容并将其从 / 写入文件。

为了做到这一点,我正在尝试编写一个程序来打印 baseclass 中的所有变量,其中包含来自 subclass 的更新,但没有 subclass 变量。

想法是 class A 是实际的 VHDL/SystemVerilog/C++ record/structure 而 class B 包含进行处理和生成 [=34 中的值的逻辑=] A.

例如:

class A(object):
    def __init__(self):
        self.asd = "Test string"
        self.foo = 123

    def write(self):
        print self.__dict__

class B(A):
    def __init__(self):
        A.__init__(self)
        self.bar = 456
        self.foo += 1

    def write(self):
        super(B, self).write()

调用 B.write() 应该产生以下结果:(注意 foo 的增量值)

"asd: Test String, foo: 124"

但它会产生

"asd: Test String, bar: 456, foo: 124".

有没有办法只获取基础 class 变量?我可以将基本字典与 subclass 字典进行比较,并只打印出现在两者中的值,但这并不像是一种干净的方式。

基本 class 和子class 变量之间没有区别。根据定义,继承是一种 is-a 关系; base class 中定义的所有内容都如同在 subclass.

中定义的一样

同样,您在代码中任何其他点在实例上定义的任何内容也将出现在字典中; Python 不限制您在 class 的其他地方甚至从外部添加新的实例变量。

做你想做的唯一方法是在你输入 A.__init__ 时记录键。

你说:"I could compare the base dictionary with the subclass dictionary and only print the values that appear in both but this does not feel like a clean way"。您尝试做的事情在 Python 中不是自然而然的事情,因此无论您做什么,都不会干净。但实际上,您的建议是不可能的,因为在 B 实例中进行 .write 调用时无法获取基本字典。最接近的做法是在 B 中调用 __init__ 之后立即复制它(或者,如 Daniel Roseman 所建议的那样,复制它的密钥),以便稍后需要时可以参考该副本.

这是执行此操作的一些代码:

class A(object):
    def __init__(self):
        self.asd = "Test string"
        self.foo = 123

    def write(self, d=None):
        print self.__dict__

class B(A):
    def __init__(self):
        A.__init__(self)
        self.parentkeys = self.__dict__.keys()
        self.bar = 456
        self.foo += 1

    def write(self):
        bdict = self.__dict__
        print dict((k, bdict[k]) for k in self.parentkeys)


a = A()
b = B()
a.write()
b.write() 

输出

{'foo': 123, 'asd': 'Test string'}
{'foo': 124, 'asd': 'Test string'}

这里有一个小变化:

class A(object):
    def __init__(self):
        self.asd = "Test string"
        self.foo = 123

    def write(self, d=None):
        if d is None:
            d = self.__dict__
        print d

class B(A):
    def __init__(self):
        super(B, self).__init__()
        self.parentkeys = self.__dict__.keys()
        self.bar = 456
        self.foo += 1

    def write(self):
        bdict = self.__dict__
        d = dict((k, bdict[k]) for k in self.parentkeys)
        super(B, self).write(d)

但是,我觉得可能有更 Pythonic 的方法 what you really want to do...