我需要使用在类的实例之间共享的变量。因此,类变量似乎符合要求。但这些类变量也在子类之间共享,这是需要避免的。
问题是这样的:
class Parent(object):
a=[]
class Child(Parent):
pass
print(Child.a is Parent.a) # => True # Need to avoid this
这是我尝试解决的方法:
可以通过将父级的类变量重新声明为 Child 来隐藏父级的类变量,但当 Child.a 再次指向 Parent.a 时,仍然可以删除子级的“a”变量。
class Parent(object): a=[] class Child(Parent): a=[] # Works, but delete-able. print(Child.a is Parent.a) # => False # Works del Child.a print(Child.a is Parent.a) # => True # Breaks again
与上一个相同,但“a”是通过元类添加的,这样更好。
class meta(type): def __new__(cls, name, base, clsdict): temp_class = type.__new__(cls, name, base, clsdict) temp_class.a=[] return temp_class class Parent(object): __metaclass__=meta class Child(Parent): pass print(Child.a is Parent.a) # => False # Works del Child.a print(Child.a is Parent.a) # => True # Breaks again
但是它们都没有解决“可能删除Child的类变量”问题。
是否可以为类变量提供某种描述符,从而使删除变得不可能?如果没有,有什么好的方法可以解决这个问题?
最佳答案
要将类属性设置为该类的私有(private)属性,而不是子类的私有(private)属性,请在其前面添加“__”(两个下划线)。这称为“类私有(private)成员”或“类私有(private)引用”。
下面的__update
在Mapping类中,但不在子类中。
class Mapping:
def __init__(self, iterable):
self.items_list = []
self.__update(iterable)
def update(self, iterable):
for item in iterable:
self.items_list.append(item)
__update = update # private copy of original update() method
class MappingSubclass(Mapping):
def update(self, keys, values):
# provides new signature for update()
# but does not break __init__()
for item in zip(keys, values):
self.items_list.append(item)
来自:Python Classes documentation
这是原始代码。请注意,Child 类不会从父类继承 __a
属性。
另请注意,Child
实例对象也不继承__a
属性。 __a
属性对于父级及其实例来说是私有(private)的,它不是继承的。
来源
class Parent(object):
__a = []
class Child(Parent):
def check(self):
print self.__a # raises exception, __a is in Parent only, not in self
try:
print(Child.__a is Parent.__a)
except AttributeError as exc:
print exc
print
try:
Child().check()
except AttributeError as exc:
print exc
输出
type object 'Child' has no attribute '__a'
'Child' object has no attribute '_Child__a'
关于python - 如何让类变量不在子类之间共享?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24019891/