类方法中的属性复制
通过使用copy可以确保A的{},无论是谁定义它,都是B扩展它之前的起点。在class A:
d = {}
@classmethod
def c(cls):
print (cls.d)
class B(A):
d = A.d.copy()
d.update({0:1})
B.c()
A.c()
输出
^{pr2}$
开发人员更改A以后,B得到{},而不触及{}的定义。在class A:
d = {2:3}
@classmethod
def c(cls):
print (cls.d)
class B(A):
d = A.d.copy()
d.update({0:1})
B.c()
A.c()
输出{0: 1, 2: 3}
{2: 3}
警告:如果d中包含其他对象,您可能需要使用^{},否则只复制第一个“级别”,所有其他对象都将引用原始对象(这在我知道它之前曾给我带来了很多悲伤!)。在
继承实例方法
字典复制是python的,很明显,B获取{}并扩展它,但是由于您可能要在用例中创建实例(比如Dog),这些类可能会使用__init__方法而缺少class instance的概念。这将允许您拥有多个具有潜在唯一性的Bs
下面是一个包含实例的类定义示例class A:
def __init__(self):
self.d = {}
def c(self):
print (self.d)
class B(A):
def __init__(self):
A.__init__(self)
self.d.update({0:1})
# create instances of each class
a = A()
b1 = B()
b2 = B()
# call each instance's c method
b1.c()
b2.c()
a.c()
# you can even update on the fly without affecting the other!
a.d.update({2:3})
b1.d.update({4:5})
b2.d.update({7:8})
b1.c()
b2.c()
a.c()
输出{0: 1}
{0: 1}
{}
{0: 1, 4: 5}
{0: 1, 7: 8}
{2: 3}