Skip to main content
 首页 » 编程设计

python之如何使子类之间不共享的类变量

2024年11月01日8lhb25

我需要使用在一个类的实例之间共享的变量。因此,类变量似乎符合要求。而且这些类变量在子类之间共享,需要避免这种情况。

问题是:

class Parent(object): 
    a=[] 
 
class Child(Parent): 
    pass 
 
print(Child.a is Parent.a) # => True # Need to avoid this 

这是我试图解决的问题:

  1. 可以通过重新声明子项来隐藏父项的类变量,但是当 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 
    
  2. 和prev一样,但是通过元类添加了“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)引用”。

下面的__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

这是原始代码。请注意,子类不会从父类继承 __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'