继承(共享)公共超类属性的子类对象的集合



我正在尝试创建一个子类来继承其超级类的属性,但同时,超级存储子类的集合对象。这是我的尝试,但我觉得这不是一种有效的方法,可能还有其他更好的方法来实现它。

class SuperCls:
    def __init__(self, a, b):
        self.a = a
        self.b = b
        self.col = []
    def addSubCls(self, cCls):
        self.col.append(cCls)
class SubCls(SuperCls):
    def __init__(self, sp, c, d):
        self.c = c
        self.d = d
        SuperCls.__init__(self, sp.a, sp.b)
    def __str__(self):
        s = 'a:{}, b:{},c:{},d:{}'.format(self.a,self.b, self.c, self.d)
        return s
sup = SuperCls(1,2)
sub=SubCls(sup,3,4)
sup.addSubCls(sub)
sub2=SubCls(sup,5,6)
sup.addSubCls(sub2)
sub3=SubCls(sup,7,8)
sup.addSubCls(sub3)
print '[%s]' % '| '.join(map(str, sup.col[0:]))
# printout:  [a:1, b:2,c:3,d:4| a:1, b:2,c:5,d:6| a:1, b:2,c:7,d:8]

关于类的设计,还有很多话没有说,这可能会对实现产生影响。

这是类似于您的实现的东西,它是一个 Python 3 实现,并且使用更少的代码行,在这方面更有效。子类容器是父类的类属性;子类实例在创建时将添加到容器中。 容器包含对对象的弱引用,以便在对象超出范围或删除时可以对它们进行垃圾回收。

import weakref
class SuperCls:
    subclass_instances = weakref.WeakKeyDictionary()
    def __init__(self, a, b):
        self.a = a
        self.b = b
        self.col = []
class SubCls(SuperCls):
    def __init__(self, a, b, c, d):
        self.c = c
        self.d = d
        super().__init__(a,b)
        super().subclass_instances[self] = str(self)
    def __str__(self):
        s = 'a:{}, b:{},c:{},d:{}'.format(self.a,self.b, self.c, self.d)
        return s

a = 1
b = 2
sub=SubCls(a,b,3,4)
sub2=SubCls(a,b,5,6)
sub3=SubCls(a,b,7,8)

这些都打印相同的东西 - 每个对象都可以访问容器。

print(' | '.join(map(str, SuperCls.subclass_instances)))
print(' | '.join(map(str, sub.subclass_instances)))
print(' | '.join(map(str, sub2.subclass_instances)))
print(' | '.join(map(str, sub3.subclass_instances)))

print(SuperCls.subclass_instances is sub.subclass_instances is sub2.subclass_instances is sub3.subclass_instances)将打印True.

最新更新