只让类访问, 而不让类的实例来访问某个成员变量

class Test(object):
    def __get__(self, instance, type=None):
        """
        只让类访问, 而不让类的实例来访问。
        具体是靠 __get__(self, instance, type=None) 方法来实现来的:
        第二个参数 instance, 当 class.attr 的时候, instance 为 None;
        当 obj.attr 的时候, instance 为 obj.
        """
        if instance != None:
            raise AttributeError("Cannot access via %s instances" % type.__name__)
        return self

class Main(object):
    test = Test()

m = Main()

print Main.test
print m.test

 

posted @ 2016-11-28 09:47  鸪斑兔  阅读(237)  评论(0编辑  收藏  举报