![](/img/trans.png)
[英]Methods to link common class attributes between objects? (not inheritance)
[英]Python: ensure class attributes are not shared between common inheritance trees
我感觉我在某处看到过这个,但我不再确定这是重建的 memory 还是真的存在。 在任何情况下,我都找不到这种情况的参考:
class A:
a = 1
class B(A): # should have it's own class attribute 'a'
pass
class C(A): # should have it's own class attribute 'a' and newly defined 'c'
c = 3
在上面的例子中, Aa is Ba is C.a
。 但是,我实际上希望它们在保持这种结构的同时分开。 这是有充分理由的,我不想讨论实例变量。 原因是在我的应用程序中,所有这些类都用作“命名空间”。 为了解决“问题”,我将A
继承的部分替换为自身的副本(伪代码):
class A:
a = 1
class B(A): # B.a resolves to A.a
pass
class C(A): # C.a resolves to A.a
c = 3
copy_func(B.A, A) # investigates public attrs of A and B and create copies, now B.a is not A.a
copy_func(C.A, A) # investigates public attrs of A and B and create copies, now C.a is not A.a
定义__init_subclass__
以在定义子类时自动复制超类属性。
import copy
class A:
a = []
def __init_subclass__(cls, **kwargs):
for base in cls.mro():
for attr in base.__dict__:
if attr not in cls.__dict__ and not attr.startswith("_"):
setattr(cls, attr, copy.copy(getattr(cls, attr)))
这将从不以_
开头的超类命名空间中复制所有内容。 在实践中,人们可能希望应用更严格的规则。
__init_subclass__
在定义子类时自动运行。 这意味着子类无需显式运行代码即可获得复制的属性。
class B(A):
pass
class C(A):
c = 3
assert B.a is not A.a
assert C.a is not A.a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.