• 通过__metaclass__为类动态增加方法实例


    def ma(cls):
        print 'method a'
    
    def mb(cls):
        print 'method b'
    
    method_dict = {
        'ma':ma,
        'mb':mb
    }
    
    
    class DynamicMethod(type):
        def __new__(cls, name, bases, dct):
            if name[:3] == 'Abc':
                dct.update(method_dict)
            return type.__new__(cls, name, bases, dct)
    
        def __init__(cls, name, bases, dct):
            super(DynamicMethod, cls).__init__(name, bases, dct)
    
    
    class AbcTest(object):
        __metaclass__ = DynamicMethod
        def mc(self, x):
            print x * 3
    
    def main():
        a = AbcTest()
        a.mc(3)
        print dir(a)
        a.ma()
    
    main()
    

      

  • 相关阅读:
    【leetcode】二叉搜索树的最近公共祖先
    052-12
    052-11
    052-10
    052-9
    052-8
    052-6
    052-5
    052-3
    052-2
  • 原文地址:https://www.cnblogs.com/bjdxy/p/2861535.html
Copyright © 2020-2023  润新知