zoukankan      html  css  js  c++  java
  • 在元类中设置隐藏属性

    在元类中对创建的类进行属性隐藏 通过控制对象的__dict__属性格式从而对属性进行隐藏。在外面访问属性需要访问隐藏属性格式。

    class Mymeta(type):
        def __init__(self,class_name,class_bases,class_dic):
            #控制类Foo的创建
            super(Mymeta,self).__init__(class_name,class_bases,class_dic)
    
        def __call__(self, *args, **kwargs):
            #控制Foo的调用过程,即Foo对象的产生过程
            obj = self.__new__(self)
            print(obj) # <__main__.Foo object at 0x0000019E54269518>
            self.__init__(obj, *args, **kwargs)
            print(self)  # Foo
            obj.__dict__={'_%s__%s' %(self.__name__,k):v for k,v in obj.__dict__.items()}
            print(obj)  # <__main__.Foo object at 0x0000019E54269518>
            return obj
    
    class Foo(object,metaclass=Mymeta):  # Foo=Mymeta(...)
        def __init__(self, name, age,sex):
            print(self)  # <__main__.Foo object at 0x0000019E54269518>
            self.name=name
            self.age=age
            self.sex=sex
    
    
    obj=Foo('egon',18,'male')
    print(obj)  # <__main__.Foo object at 0x0000019E54269518>
    print(obj.__dict__)
    

      

  • 相关阅读:
    my first android test
    VVVVVVVVVV
    my first android test
    my first android test
    my first android test
    ini文件
    ZZZZ
    Standard Exception Classes in Python 1.5
    Python Module of the Week Python Module of the Week
    my first android test
  • 原文地址:https://www.cnblogs.com/Roc-Atlantis/p/9254422.html
Copyright © 2011-2022 走看看